简体   繁体   中英

Symfony2 include javascript file

i'm new to symfony, i have a problem that is bothering me for several minutes: I want to include in my project a JS file but it doesn't seem to work(nothing happens in the browser, like there is no javascript included).I installed the assets from the console,and now the css, images and JS files are stored in the web/bundles directory. In my view i wrote:

{% javascripts %}
<script src = "http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="{{ asset('bundles\emagmagazine\js\javascript.js') }}"></script>
{% endjavascripts %}  

What am i doing wrong?

I do it like this in my templates:

{% javascripts "@asset_name_1" "@asset_name_2" %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

The asset_name_X are the names of the assets in assetic configuration.

you run the command: php app/console assets:install web ???

edit: check with the inspector or firebug if the .js file is loaded

Change your javascript block as follows

{% block javascripts %}
    {% javascripts 
        'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', 
        '@emagmagazine/Resources/public/js/*' 
     %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

That's the correct way to handle them.

You forgot to use the correct block.
Moreover, that way, assetic will handle (download and make available) the external js you're calling here

Just try sepecifying the script type:

<script type="text/javascript" src="{{ asset('assets/plugins/jquery/jquery.min.js') }}"></script>

or add the path to your base.html.twig if you are using the norm, and call it in your twig:

{% block javascripts %}
{{ parent() }}
{% endblock %}

As it written here : http://symfony.com/doc/current/cookbook/assetic/asset_management.html#including-javascript-files

You just include your files like :

{% block javascripts %}
    {% javascripts '@EmagmagazineBundle/Resources/public/js/*' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

For CDN files, the best you can do is juste include normally like:

<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>

If you insert CDN in your {% javascripts %} it will work but you lose the utility of CDN is to have a common library on different websites

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM