5

I am new in Symfony2 framework and not fully understand how to work with javascripts and how to include theirs in the best way.

What I need: to include jQuery script to each page.

What I have: I have common layout like this:

<!DOCTYPE html>
<html>
    <head>
        {% block javascripts %}{% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}

    </body>
</html>

Where jquery.js should be placed. What about web/bundles/jquery? Or there are some special official jquery bundles? Should I use asset() and how?

1
  • I have answered a similar question here. You shouldn't put vendor libs to your own bundles. Use 'app/Resources/...' for any front-end libs. Commented Aug 17, 2012 at 20:53

4 Answers 4

13

Assuming your jquery.min.js is placed under src/Acme/FooBundle/Resources/public/js/

You can use either

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

or

{% javascripts
    '@AcmeFooBundle/Resources/public/js/jquery.min.js'
%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

Into your twig template.

Make sure you installed the assets afterwards or run this command

php app/console assets:install web --symlink
Sign up to request clarification or add additional context in comments.

Comments

9

There are several ways to include jQuery in a Symfony project. You can:

1. Install jQuery with a front-end package manager (Bower)

The Symfony documentation states:

Bower is a dependency management tool for front-end dependencies, like Bootstrap or jQuery.

If Bower isn't already installed, you can install it globally with npm (require node):

npm install -g bower

According to the Symfony documentation:

A bundle should not embed third-party libraries written in JavaScript, CSS or any other language.

So, we store jQuery directly in the web/ directory which is publicly accessible. To tell Bower where to install packages, create a .bowerrc file in your Symfony project root with this content:

{
    "directory": "web/assets/vendor/"
}

Execute bower init in your project root to create bower.json which will define installed packages. Type enter for every question to answer the default value (select 'globals' for the type of modules).

Bower is ready to install jQuery in your project:

bower install --save jquery

Now you can include jQuery in your template:

<script src="{{ asset('assets/vendor/jquery/dist/jquery.min.js') }}"></script>

Currently Bower does not have a "lock" feature like on Composer. That's why you should probably commit the assets downloaded by Bower instead of adding the directory to your .gitignore file. This will probably change in the future: bower/bower#1748.

2. Install jQuery with Composer

Even if Composer is a dependency manager for PHP, you can also use it to install jQuery.

To make Composer able to install components like components/jquery, you need first to add the component-installer:

composer require robloach/component-installer

Then modify your composer.json file to include:

"require": {
    "components/jquery": "3.1.1"
},
"config": {
    "component-dir": "web/assets/vendor"
},

and execute composer install. This will install jQuery in the web/assets/vendor directory.

You can then include jQuery in your template:

<script src="{{ asset('assets/vendor/jquery/jquery.min.js') }}"></script>

3. Include jQuery from a CDN

For example with Google CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

About advantages and disadvantages to using a CDN, I suggest you to read this page.

In all cases:

To make sure your scripts (which require jQuery) will work, jQuery has to be loaded first. So, depending on your page loading requirements, you should either:

  • include jQuery just before you need it, or
  • include it in the <HEAD>, or
  • use defer in your scripts

2 Comments

The composer way does not install the folder in the component-dir path. It steel install it in the vendor folder
It installs well jQuery in web/assets/vendor, I just tested it. Pay attention to update composer.json before executing composer install. If composer install installs nothing, use composer update instead.
0

For the sake of purity. Of course the <script> tags should be closed, so the correct code snippets are:

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

and

{% javascripts '@AcmeFooBundle/Resources/public/js/jquery.min.js' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

Otherwise the whole content of the page would be treated as the content of the script tag and would appear blank.

2 Comments

For unknown reasons, using html-legal singleton (self-closing) script tag breaks the sf-toolbar (on chrome at least). bad: <script src="{{ asset('bundles/jquery/jquery.js') }}" /> Using the empty-but-closed tag works. Good: <script src="{{ asset('bundles/jquery/jquery.js') }}" type="text/javascript" ></script>
@dman self closing script tags are not valid HTML as per W3C HTML4 / 5 or XHTML specifications. w3.org/TR/html4/interact/scripts.html#h-18.2.1 It must contain both start and end tags.
0

For implementation with a composer package, navigate to your symfony package and run the following commands.

Download Vendor Package:

The package you choose is up to you, I am using a popular package (bmatzner/jquery-bundle) for this example.

php composer.phar require bmatzner/jquery-bundle:2.* for jQuery 2.x

or

php composer.phar require bmatzner/jquery-bundle:1.* for jQuery 1.x

Add The Bundle to your AppKernel:

/* /app/AppKernel.php */

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Bmatzner\JQueryBundle\BmatznerJQueryBundle(),
    ///...

Install Assets:

php bin/console assets:install --symlink web

To include in template:

<!-- /app/Resources/views/base.html.twig -->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}
        <script type="text/javascript" src="{{ asset('bundles/bmatznerjquery/js/jquery.min.js') }}"></script>
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
    <body>
        {% block body %}{% endblock %}
        {% block javascripts %}{% endblock %}
    </body>
</html>

Clear Cache:

php bin/console cache:clear --env=dev
php bin/console cache:clear --env=prod

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.