Silent
Silent

Reputation: 87

Flask and jinja2 include tag

How to do it "include tag" in jinja2. I need to output a block of articles in the base template. And they work in children.

views.py

Articles.query.filter_by(name=name).first()

base.html

{% block content %}
    Content base
{% endblock %}
---{{ this_articles_tag }}----

children.html

{% extends 'base.html' %}
{% block content %}
    Content children
{% endblock %}
---{{ output Articles }}----

Django in this "include tag", how to do it in jinja2? (Without using context_processor)

Upvotes: 2

Views: 3037

Answers (1)

Ignas Butėnas
Ignas Butėnas

Reputation: 6307

If you need to include another template in the template, just use include in Jinja. But if you are talking about template tags (in Django I remember I liked them a lot), then in Flask only your mentioned context_processor is the way to go. Which I think is not a bad thing at all.

Edit:

Easiest way to get context processor registered as a function is pointed in the documentation.

But if you want something more fancy, like dynamic loader or you will load your functrion from different places, then you can define your own decorator function, which basically wraps the function which returns dictionary:

def example_templatetag():
  def get_something():
    return get_want_you_want_from_db()
  return dict(get_something=get_something)

Then where you create your Flask app object you can easily register this function:

app.context_processor(example_templatetag)

And then in a template you can use is like:

{% set data_you_wanted=get_something() %}
{{ data_you_wanted }}

But maybe for you the way mentioned in documentation will be more than enough ;)

Upvotes: 2

Related Questions