rihekopo
rihekopo

Reputation: 3350

Link to script in only one Jinja template

I have one line of code that I would like to add to the head of my Jinja2 HTML page. I could easily add it as any other meta tags or etc, but I need this code in only one page, therefore no reasons to keep it in the site's header.

I tried to pass it as a string to render_template, but it didn't appear in the final render.

@app.route('/page')
def page():
    str = "<script src='https://site.xy/api.js'></script>"

    return render_template('page.html', script_string = str)

page.html:

{% extends "layout.html" %}
{{script_string}}
{% block content %}

I also tried to do it in the layout file with blocks, but it failed too.

{% block js %}<script src='https://site.xy/api.js'></script>{% endblock %}

How can I add a script tag to the head of page.html without adding it to any other pages?

Upvotes: 1

Views: 816

Answers (1)

davidism
davidism

Reputation: 127180

Use the block, but leave it empty by default, and set it in page.html.

layout.html:

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

page.html:

{% block head_js %}<script src='https://example.com/api.js'></script>{% endblock %}

Upvotes: 5

Related Questions