M
M
My joy2014-08-29 09:38:37
PHP
My joy, 2014-08-29 09:38:37

How to inject Twig template variable into external js ?

Hello! :)
There is a site where twig template engine variables are substituted directly into js on the page. something like this:
alert( "{{ alrt_message }}" );
but you need to close all scripts from indexing, taking them out into separate files and closing them through robots
and, of course, in the external file when generating the page, instead of the variable value, there will be the text itself,
{{ alrt_message }}
tell me the solution, how can I remove scripts from the main content of the page while saving the twig file 'a
Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
My joy, 2014-09-19
@t-alexashka

Actually, I've already come up with a solution. Create a function in php, which will show in js format everything that is transferred to it by the getom. Thus, without calling the script, I will substitute the necessary data in the link, and the browser will load them as if it were js.
I will end up with something like:

getdata = {
   var1:"23",
   var2:"hello"
}

just what you need - the scripts themselves will not be on the page.

A
Artyom Shanin, 2017-09-21
@JoyMefisto

{% set protected_fields = protected_route_info(protectedRoute, [], true).code %} {# получаем переменную в twig #}

<script> // и пробрасываем её в script
    (function () {
        let protectedFields = {{ protected_fields|json_encode|raw  }};

        console.dir(protectedFields);
    })();
</script>

S
Sergey, 2014-08-29
Protko @Fesor

And what does indexing, robots.txt and external js files have to do with it?

Y
YEASTOR, 2014-09-19
@YEASTOR

The external file must contain a function that accepts parameters. Call this function in twig.
twig.js
_

function alertMessage(message){
   alert(message);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question