Including Blocks from Jinja templates - python

I would like to include blocks from templates instead of macros, as many templates will be including content from many other templates, so extends isn't an option.
I've read many answers about this, including blocks in included files, but the use case always seems to be different. I suspect this cannot be done.
template1.html
{% block description %}
<p> Here is a description </p>
{% endblock %}
And in template2.html
{% from 'template1.html' import description %} <- doesnt work

You have two options here.
Use a macro, which sounds like something you don't want to do.
Use a template_filter.
Assuming you're using Flask, this is as easy as:
#app.template_filter('get_block')
def template_filter(block, file):
html = render_template(file)
# Then use regex or something to parse
# or even simple splits (better with named blocks), like...
content = html.split('{%% block %s %%}'%(block))[-1]
content = content.split('{%% endblock %%}')[0]
return content
And to use it:
{% 'description'|get_block('template1.html') %}

Related

Highlighting the inner code blocks in Django Template Engine with django-pygmentify

I'm using django-pygmentify package in order to highlight my code blocks in my Django templates. The thing is that this package only supports code blocks as input. I have a model field that keeps markdown data. This markdown content might contain code blocks. (using ``` symbol)
Now, how can I highlight its inner code blocks??
Imagine I have a field that only contains source code. Like:
print('Hey..!')
In that case, this one works properly.
{% load pygmentify_tags %}
...
{% pygmentify %}
{{post.code}}
{% endpygmentify %}
Imagine my field contains the following content.
## Hello
This is my first step working with Python.
```python
print('Hey..!')
‍```
In this case, how can I implement it?? I can render that whole markdown content with {{post.body|markdown|safe}}, but how can I highlight those code blocks?? I also want to give all those code blocks a class name .code-block for better styling. Should I create a custom template tag?
You may use html standard <code> tag like this:
{% load pygmentify_tags %}
...
{% pygmentify %}
<code>
{{post.code}}
</code>
{% endpygmentify %}
This will separate the code section and at the same time will apply pygmentify to it.

Break long {% with %} assignment into multiple lines in a Django template [duplicate]

I am creating a custom django template tag by using such a code :
#register.simple_tag(takes_context=True)
def render_listing(context, *args, **kwargs):
... my code ...
This works well, but in my template, it seems that all parameters must be on a single line, for example :
this works:
{% render_listing param1=val1 param2=val2 ... paramN=valN %}
but on multiple lines, it does not work :
{% render_listing param1=val1
param2=val2
...
paramN=valN %}
I tried multiple escape sequences but I did not succeeded,
Is there a way to specify a template tag on multiple lines ?
No, the Django template language does not support multiple line tags. See ticket 8652, which was closed as WONTFIX, or this thread from the django-developers mailing list.
Sometimes, if there is a repeated prefix, you can make it more readable by using the with tag. For example if you have,
{% render_listing param1=long.common.prefix.val1 param2=long.common.prefix.val2 param2=long.common.prefix.val3 %}
you could rewrite as
{% with prefix=long.common.prefix %}
{% render_listing param1=prefix.val1 param2=prefix.val2 param2=prefix.val3 %}
{% endwith %}
Often (but not always), a really long tag is an indication that you're putting too much logic in the template. See if you can move some of it into the view, model method, template tag or template filter.
It's pretty straightforward to enable, though hackish:
import re
from django.template import base
base.tag_re = re.compile(base.tag_re.pattern, re.DOTALL)
"Using" it is simple; one place I find it especially useful is {% include %} tags:
{% include 'my/sweet/modal-template.template' with
message="Hey, do you really want to frob the widget?"
yes="Heck yes I do!"
no="No frickin' way!"
icon="error"
%}
I haven't tested this in more recent versions of Django but I imagine it could be adapted; that worked at least back around 1.8. I should point out that in theory some tags that do custom parsing of their arguments could break; in practice I haven't had any trouble in the last ~10 years of Django programming.

How to avoid rendering a block in a base template - or: how to define a multiline block-like variable?

I am rather new to jinja, so please excuse this potentially dumb question ...
I have a jinja macro sitting in a file named lib.jinja which looks as as follows
{% macro some_macro(some_content) %}
<div class="some_class">{{ some_content }}</div>
{%- endmacro %}
I import it from another file named content.htm, which looks roughly as follows:
{% from "lib.jinja" import some_macro %}
{% block content %}
Some content
{% endblock %}
{{ some_macro(self.some_macro(self.content())) }}
The rendered output looks as follows:
Some content
<div class="some_class">Some content</div>
Notice that the content appears twice, once rendered through/by the macro, another time - directly above - rendered like it was defined in the block named content in content.htm. I would love to avoid that the block is rendered twice - it is supposed to be fed into the macro and rendered through it only.
I appears that I can "work around" it by turning content.htm into a child template (by adding an extends tag at its top) of an empty base template.
Maybe I have a lack of understanding for the concepts here: A block is not a variable - I get that. If there is no extends tag, the template is treated as a base template, I assume. If there are no child templates or other directives, I guess the block is just rendered as-is and then, for a second time so to speak, picked up by the macro - correct?
How can I solve this in a sane manner, i.e. how could I handle this other than by extending an empty base template? Is there another type of block or variable that would fit my needs?
Just after I submitted this question, I finally found what I was looking for in the manual: Block Assignments.
{% from "lib.jinja" import some_macro %}
{% set content %}
Some content
{% endset %}
{{ some_macro(self.some_macro(content)) }}
The set and endset tags solve my problem.

Django template: Translate include with variable

I have a template in which you can pass a text variable. I want to include this template into another one but with a translated text as it's variable. How can you achieve this?
I would like something like this:
{% include "a_dir/stuff.html" with text={% trans "Load more promotions" %} %}
I tough about writing my own template tag that will perform a ugettext but then when creating the .po file, the text variable will not be taken automatically.
I don't want to do this work in the view since all our translations take place in the templates.
You can put the translated string into a variable with the as syntax. For instance:
{% trans "Load more promotions" as promotions %}
{% include "a_dir/stuff.html" with text=promotions %}
See the docs for more details.
A shorter way is
{% include 'a_dir/stuff.html' with text=_("Load more promotions") %}
which also works fine with variables

In Jinja2, how can I use macros in combination with block tags?

I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses macros to support passing of arguments.
My base template contains this code (edited for simplicity):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
{% from "foo.html" import macro1, macro2, macro3 %}
{% macro base_template(title=none, arg2=none, urls={}, arg3=false) %}
<html>
<title>{{ title }} | Site.com</title>
....
{{ caller() }}
....
</html>
{% endmacro %}
{% block content %}{% endblock %}
And my pages that extend it look like this:
{% extends "base.html" %}
{% block content %}
{% call base_template(title="home", arg2="active", arg3="true") %}
(html code here)
{% endcall %}
{% endblock %}
So basically all the pages extend base, they call a macro and pass arguments to that macro. I don't quite understand it all, but the main point is that this allows default values and a degree of flexibility that doesn't require redefining an entire block: it gives some degree of flexibility and power. Again this is heavily simplified.
The only problem is, this negates my ability to use blocks. Macros are for flexibility, but with blocks, I have the ability to override something entirely, or use it's parents contents and add to it, which I can't do with Macros (at least I don't think). The problem is, I can't wrap things in blocks, else they won't see the values in the macro. For instance, doing this:
{% block title %}<title>{{ title }} | Site.com</title>{% endblock %}
Will fail because it will say title is undefined.
Ultimately I am looking for a way to utilize both the power and organiztional aspects of blocks, but still be able to utilize the logic & terseness of macros. If anyone could give me any help as to how I might go about this problem, I would really appreciate it.
Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a set tag will be accessible from the template it is extending. For example, if you have a template named layout.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<title>{{ title }} | Site.com</title>
....
{% block content %}{% endblock content %}
....
</html>
And you have this child template, index.html:
{% extends "layout.html" %}
{% set title = 'Homepage' %}
{% block content %}
(html code here)
{% endblock content %}
Then the reference to title in the parent would resolve to 'Homepage'. You can do this with any type of variable. For what you're doing, I don't think there is any need for macros - if you take advantage of this feature and place blocks well, you will be able to do pretty much everything you need to do as far as layouts are concerned. I would look at some of the templates used by Plurk Solace, which is written by one of the Jinja2 authors, if you want to get a good idea of when to use various features of Jinja2.

Categories