Question

I am trying to clean up my html output in a Symfony2 Project. What really bothers me is that I dont really know how to export inline JS dynamically. For example: I need to initialise Jquery Datatables, but not on every page, most of the pages have their own specific inline js. Im searching for a way to just extend a twig block with my js snippets, that gets grouped together and loaded by assetic from an external (virtual) .js file.

Was it helpful?

Solution

Yes, you need to use template inheritance and have a parent javascript/jquery block. Jquery is the same as javascript so you can include that in one block or have a seperate one. If you are using a variable, then pass that variable to the base jquery section. For your different pages, you need to extend the base twig file and either add to the javascript block by including the parent or overriding it entirely.

base twig file has basic html layout with js and css blocks:

<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
            <title>{% block title %}{% endblock %} - My Webpage</title>
        {% endblock %}
        {% block js %}
            <script src="{{ asset('js/main.js') }}"></script>
        {% endblock %}

    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>

This is inherited by the child page

{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block js%}
    {{ parent() }}
    <script src="jquery.plugin.js"></script>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome on my awesome homepage.
    </p>
{% endblock %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top