1
votes

As we can read in Symfony2 documentation, JavaScript files have to be declared at the bottom of body tag.

However, if I declare jQuery library in layout template and if I want to use jQuery in child template I have this errorĀ :

$ is not defined

It seems jQuery is loaded after my script tag. When I put an alert message at the top of jQuery file, alert is displayed.

Any idea to load jQuery before ?

Find below my base, layout and child templates.

app/Resources/views/layout.html.twig:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        {% block stylesheets %}
                {# ... #}
        {% endblock %}
    </head>

    <body>            
        <div id="container">
            {# ... #}
        </div>

        {% block javascripts %}
        {% endblock %}
    </body>
</html>

src/MyBundle/resources/views/layout.html.twig:

{% extends "::layout.html.twig" %}

{% block main %}
    {% block mybundle_body %}
    {% endblock %}
{% endblock %}

{% block javascripts %} 
    {% javascripts
        '@MyBlogBundle/Resources/public/js/jquery-1.8.3.min.js' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock javascripts %}

src/MyBundle/resources/views/MyBundle/modify.html.twig:

{% extends "MyBundle::layout.html.twig" %}

{% block mybundle_body %}

    <script type="text/javascript">
    // Enable the file uploader
    $(function() { // my error here : $ is not defined
        new PunkAveFileUploader({ 
            {# ... #}
        });
    });
    </script>
{% endblock %}

Many thanks.

2

2 Answers

4
votes

Well, like you said, jQuery is loaded after your <script> tag, so when your script tries to use jQuery (with the $ sign), jQuery is not yet defined.

I'd move the {% block javascripts %} to the head tag.

2
votes

You can build a new inheritance. So your script will always be after your jQuery.

{% block javascripts %} 
    {% javascripts
        '@MyBlogBundle/Resources/public/js/jquery-1.8.3.min.js' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    {% block script %}
    {% endblock script %}
{% endblock javascripts %}

src/MyBundle/resources/views/MyBundle/modify.html.twig:

{% extends "MyBundle::layout.html.twig" %}

{% block mybundle_body %}
   //some stuff
{% endblock %}

{% block script %}

<script type="text/javascript">
    // Enable the file uploader
    $(function() { // my error here : $ is not defined
        new PunkAveFileUploader({ 
            {# ... #}
        });
    });
    </script>
{% endblock %}