Flask - use decorator and route param to render data with custom jinja2 tag Flask - use decorator and route param to render data with custom jinja2 tag flask flask

Flask - use decorator and route param to render data with custom jinja2 tag


This answer has been updated with improved information on routing and an example in keeping with the question.

There are now three examples:- simple, improved and elegant.

1.

Simple solution is to use Jinja's Block content function in your base.html template's head section.

base.html:

<meta name="description" content="{% block description %}{% endblock %}" /><meta name="keywords" content="{% block keywords %}{% endblock %}" /><meta name="author" content="{% block author %}{% endblock %}" /><meta name="foo" content="{% block bar %}{% endblock %}" />

Then from any child.html you can set the block content, like so:

{% block description %}description from your child page.{% endblock %}{% block keywords %}website, blog, coding{% endblock %}{% block author %} {{ author.fullname }} {% endblock %}{% block bar %}foo bar content{% endblock %}

Updated...

2.

View.py

@app.route('/some-route/<slug>')def action():    foo='bar'   ping='pong'   return render_template('child.html', foo, ping)

Not sure why your meta_data is a decorator here, so changed my example.

base.html

<html><head>    {% block metadata %}{% endblock %}</head>...

child.html

{% extends "base.html" %}{% block metadata %}   <meta name="meta_tags" content="{{ foo }}{{ping}}" />   <meta name="description" content="{{ foo }}" />   <meta name="keywords" content="{{ ping }}" />{% endblock %}

3.

Elegant & concise alternative:

View.py

@app.route('/some-route/<slug>')def action():   metadata = {'keywords': 'foo', 'description': 'bar'}   return render_template('child.html', metadata=metadata)

N.B: base.html remains the same.

child.html

{% extends "base.html" %}    {% block metadata %}    <ul>    {% for key, item in metadata.items() %}       <meta name="{{ key }}" content="{{ item }}" />    {% endfor %}    </ul>{% endblock %}

More information can be found on Jinja templates, using Block content and template inheritance at: http://jinja.pocoo.org/docs/dev/templates/#template-inheritance


The solution would be to add blocks to your meta fields in base.html

The base.html file should look like this

<html>  <head>    <meta name="slug" content="{% block slug %}{% if slug %}{{slug}}{%else%}Some sane defaults if needed{% endif %}{% endblock %}" /></html>

Then in your view you should return as follows:

@app.route('/')def index():  return render_template('filename.html', slug=slug)

So if you pass slug in a render_template function it will be automatically added to your meta field.Or you will be able to modify it in child template by adding

{% block slug %}value{% endblock %}