nowiko
nowiko

Reputation: 2557

Pass variable from twig to js

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?

Upvotes: 19

Views: 51095

Answers (4)

Jairo Rodriguez
Jairo Rodriguez

Reputation: 396

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);
}

Upvotes: 3

numediaweb
numediaweb

Reputation: 17010

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);

Upvotes: 1

qooplmao
qooplmao

Reputation: 17759

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;

Upvotes: 31

fire
fire

Reputation: 21531

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

<script>
var foo = '{{ foo }}';
alert(foo);
</script>

Upvotes: 35

Related Questions