简体   繁体   中英

Rendering Markdown to multiple blocks in Jinja2 Template

So lets say I have a base template and I want to have two blocks - one named primary and one named secondary. When I go to write my markdown file, is it possible to render sections of my markdown to both blocks? I was reading through markdown documentation and Jinja documentation and I didn't really see a clear answer to this as far as I could tell.

You can create a base template that contains as many blocks as you would like, and then define new pages that extend the base template and define the content that should go in those blocks. A simple example:

base.html

<div>
{% block my_primary_block %}
{% endblock %}
</div>

<div>
{% block my_secondary_block %}
{% endblock %}
</div>

Now, supposing you want to populate those blocks from another HTML file, you could define the content of each block:

article.html

{% extends "base.html" %}

{% block my_primary_block %}
Hello world!
{% endblock %}

{% block my_secondary_block %}
Goodbye world!
{% endblock %}

but since you asked about markdown, you can use variables from articles using {{ article.variable_name }} from the HTML, and then define variable_name in an article header. For example,

article.html

{% extends "base.html" %}

{% block my_primary_block %}
{{ article.primary }}
{% endblock %}

{% block my_secondary_block %}
{{ article.secondary }}
{% endblock %}

then in your article, you just add those fields to the metadata for the article:

content/my_blog_post.md

Title: My cool blog post
Date: 2000-01-01 00:00
Primary: Hello world!
Secondary: Goodbye world!

This is the content of my cool blog post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM