Search code examples
flaskjinja2

Include js library in Jinja with css


I want to create an html template for a quilljs, a wysiwyg editor. However it requires some js and css files to work. I tried to use block like this:

main.html

<head>
    {# some csss import #}
    {% block head %}
    {% endblock %}
</head>
<body>
    {# some html #}
    {% include 'quill.html' %}
</body>

quill.html

{% block head %}
<link rel="stylesheet" type="text/css" href='{{url_for("static", filename="css/quill.snow.css") }}' rel="stylesheet" />
{% endblock %}

{# Some html template for quill #}

However it does not work. Is there a way to have a template that add js and css inside the header with jinja ?


Solution

  • The include tag will insert the target template to the current location, while your intention is to inject code to the <head> section. I would suggest switching your logic to a different design:

    a skeleton.html template where you define all the customizable sections of your html body:

    <head>
    {% block head %}
    {% endblock %}
    </head>
    <body>
    {% block body %}
    {% endblock %}
    </body>
    

    the template that will be including the sections you want to inject in your skeleton.html, lets call it quill.html here:

    {% extends "skeleton.html" %}
    
    {% block head %}
    <link rel="stylesheet" type="text/css" href='{{url_for("static", filename="css/quill.snow.css") }}' rel="stylesheet" />
    {% endblock %}
    
    {% block body %}
    <p> this is the quill page</p>
    {% endblock %}
    

    from your flask route you will be rendering the quill.html.