Search code examples
jquerytwig

Symfony and Jquery : $ is not defined


With Symfony, I create a form and form template for my collection :

{% block _training_versions_entry_dates_widget %}
    ...

    <script type="text/javascript">
        var datesCount = {{ form|length }};

        $(function () {
            $('#add-another-email').click(function(e) {
                ...
            });
        });
    </script>
{% endblock %}

But I have this error : Uncaught ReferenceError: $ is not defined

I load Jquery in my base.html.twig :

<body>
    {% block body %}{% endblock %}
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="{{ asset('/js/app.js') }}"></script>
    {% block javascripts %}{% endblock %}
</body>

I think because my theme is called before Jquery, but I don't want to move jquery in my <head>. Can you help me ?


Solution

  • Your js code must be called after jquery loading. So you can do something like this in your layout, add a block for the js code before the </body> tag:

    layout.html.twig:

    {% block javascripts_footer %}
        <script src="{{ asset('vendor/jquery/jquery.min.js') }}">            
    {% endblock %}
        </body>
    </html>
    

    Then, in your template, write your js in the javascripts_footer block, not in the content one:

    {% block javascripts_footer %}
        {{ parent() }}
        <script>
            $(document).ready(){
                var datesCount = {{ form|length }};           
                $(function () {
                   $('#add-another-email').click(function(e) {
                       ...
                    });
                });
            });
        </script>
    {% endblock %}