1
votes

I'm pretty new to Symfony2 framework and still don't really understand how to include JQuery lib after reading the following documentation http://symfony.com/doc/current/cookbook/assetic/asset_management.html#dumping-asset-files

I've seen similar questions but none of them explain how everything work together? And why we need to dump assetic? Why including them in the template is not enough?

Basically, what I want to do is to put my JQuery lib under app/Resources/js/ Then in any of my Twig template inside any of my bundle I want to refer/include this JQuery lib to be able to write a JQuery script code. Do I need to modify my app/config/config.yml file?

Please provide me with an example along with your explanation. The following is what I've done so far (all the following are in one Twig template):

{% javascripts 'app/Resources/js/jquery-1.8.0.js' %}
<script type="text/javascript">
$(document).ready(function (){
    $('a').click(function(event){
        $('#box').fadeOut();
    });
}); 
</script>
{% endjavascripts %}

<div id="box">
    <a href="#">click me</a>
</div>

The page is loaded without any problems but when I click on 'click me' the JQuery code doesn't get executed!

1

1 Answers

6
votes

You are missing something from your assetic twig implementation. You should do:

{% javascripts 'app/Resources/js/jquery-1.8.0.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
...

Without this second line, jquery is not actually loaded.

In any case, the use of assetic is optional. If you don´t feel comfortable with it, you don´t need the optimizations it provides or prefer to use something more familiar until you get the hang of it, then just put the jquery file somewhere in your 'web' folder (for example under a js subfolder) and then load it like you would load any other asset file:

<script src="{{ asset('/js/jquery-1.8.0.js') }}" type="text/javascript"></script>