4

I have a chart generated in script.

{
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
},

This is what I want to do (and I know this is not correct).

{
    "country": "{{ entry.country }}",
    "visits": {{ entry.visits }},
    "color": "#FF6600"
},

What do I need to do?

0

1 Answer 1

9

Is the JavaScript inline in your template file? e.g. using {% includeJs %} or even just a <script> tag? If so you should be able to do it as you suggested by outputting Craft variables directly into the JavaScript within your template.

If the function is in an external script, you could call a function from within your template, something along these lines:

{% includeJsFile "/path/to/myfile.js" %}
{% set myJs %}
   myFunction('{{entry.country}}','{{entry.visits}}');
{% endset %}   
{% includeJs myJs %}

And then in your JS file you can have something like

function myfunction(country, visits){
   //do something
}
2
  • 4
    Another tip: you can use the json_encode filter within the includeJs tags to pass a Twig array to the JS like so: {% includejs %}myFunction({{ myArray|json_encode|raw }});{% endincludejs %}
    – carlcs
    Commented Oct 5, 2016 at 13:15
  • useful tip @carlcs, i didnt know that :)
    – alexr
    Commented Oct 5, 2016 at 13:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.