19

Is there some way to pass variables from twig to javascript file that lay in public/js directory of bundle. Or do I need to assign my variables in template and then include my script file where vars will be used?

4 Answers 4

35

Assign the variable in the template and pick it up with javascript...

<script>
var foo = '{{ foo }}';
alert(foo);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Be aware. If you are passing user input, that variable should be escaped.
31

Another way without having to have your javascript file as a template would be to have the javascript value as a data-* attribute and then get that from your javascript file. This would mean that your javascript wouldn't necessarily be coupled to your twig file.

<a href="#" data-id="{{ entity.id }}" id="some-link">Link</a>

With jQuery..

var id = $('#some-link').data('id');

With regular javascript (i think)..

var id = document.querySelector('#some-link').dataset.id;

3 Comments

This answer is better than the accepted one IMO because you don't need to insert js in twig template.
This worked for me. To get data attribute value, I use var id = document.getElementById('video-id').getAttribute('data-id');
Be aware that if you pass something else than a numeric id you might end up having problems. Specially, user input. Using |e('html_attr') should be the correct way.
3

watch this

variable in twig:    fpoint = [{'id': 1},{'id': 2}]

if it is an array

var fg = $.parseJSON('{{ fpoint | json_encode | raw }}');
for(k in fg){
  console.log("fpoint: ", fg[k].id);
}

1 Comment

Once the initial knee-jerk reaction of "gods this is horrible" is passed, serializing to JSON and back is probably the least bad way of passing actual data structures instead of just strings in parsed javascript templates.
1

You can use this in your twig

<script type="text/javascript">
    /* <![CDATA[ */
    var settings = {
        example: {{ 'something' | trans }}
        }
    };
    /* ]]> */
</script>

then you can access them in your js:

console.log(settings.example);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.