Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  163] [ 4]  / answers: 1 / hits: 16832  / 9 Years ago, sun, may 31, 2015, 12:00:00

I'm working on a Symfony2 project and I want to call a JavaScript function and pass an array of JSON objects (which I get from a controller) from a Twig.



But a first, very simple test already failed, like:



main.js:



function helloWorld(name) {
console.log(hello + name);
}


linked to main.js in the twig and called the function:



<body>
<script>helloWorld(world!)</script>

{% block javascripts %}
<script src={{ asset('js/main.js') }}></script>
{% endblock %}
</body>


which results in a ReferenceError:




Uncaught ReferenceError: helloWorld is not defined




What do I have to do differently to make this work?



EDIT: Thanks to the two who took the time to answer. The described twig actually consists of a bunch of nested twigs and the placement of the javascript include was based on the Symfony documentation, guess that's why I didn't see the obvious. Should have detected the problem myself when phrasing the question though....


More From » symfony

 Answers
62

Invert the order of the functions:



<body>
{% block javascripts %}
<script src={{ asset('js/main.js') }}></script>
{% endblock %}

<script>helloWorld(world!)</script>
</body>

[#66392] Thursday, May 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisa

Total Points: 514
Total Questions: 93
Total Answers: 93

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;