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

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

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

<p>And then in your JS file you can have something like</p>

<pre><code>function myfunction(country, visits){
   //do something
}
</code></pre>

CC BY-SA 3.0
2016-10-05T13:15:42.217Z
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
CC BY-SA 3.0
2016-10-05T13:56:14.160Z
useful tip @carlcs, i didnt know that :)
alexr
CC BY-SA 3.0
2016-10-05T13:05:26.597Z
2016-10-05T16:57:23.597Z
2016-10-05T16:57:23.597Z
alexr
<p>I have a chart generated in script.   </p>

<pre><code>{
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
},
</code></pre>

<p>This is what I want to do (and I know this is not correct).</p>

<pre><code>{
    "country": "{{ entry.country }}",
    "visits": {{ entry.visits }},
    "color": "#FF6600"
},
</code></pre>

<p>What do I need to do?</p>

<templating>
How can I pass a Craft Field into a JavaScript function?
# How can I pass a Craft Field into a JavaScript function?

(Asked by: username_0 on 2016-10-05)

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?

**Tags:** templating


---

## 1 answers

### Answer by username_1 on 2016-10-05. Score: 9 | Accepted answer

Is the JavaScript inline in your template file? e.g. using `{% includeJs %}` or even just a

> **Comments:**
> **username_2**: 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 %}`  
> **username_1**: useful tip @username_2, i didnt know that :)  

---

