Flask | JINJA 2: render_template_string() with macro imported in context - python-3.x

I am looking to make macros available inside of the articles for my flask blog. When the body of my blog changes I run the following code to render the body into HTML:
target.body_html = bleach.linkify(bleach.clean(render_template_string(value),tags=allowed_tags, attributes=allowed_attr, strip=True))
render_template_string(value) is the part I'm concerned about. To use a macro inside of the template string (value), every single string has to include the following in order for me to use the macros from this file in the article body:
{% import "includes/macros.html.j2" as macros %}
This would not be reasonable to ensure that writers have access to the macros that I write in all of their articles. Is there any way to pass that argument via the render_template_string() function so that it doesn't have to be defined in every string? Or to otherwise create a template that the string is rendered inside of? Something like the following:
render_template_string(string,macros=function_to_import_macros("includes/macros.html.j2"))

While there does not appear to be a solution to pass an entire macros template as context, get_template_attribute does appear to allow you to pass individual macros one at a time. Example:
includes/macros.html.j2:
{% macro hello() %}Hello!{% endmacro %}
{% macro hello_with_name(name) %}Hello, {{ name }}!{% endmacro %}
Template rendering code:
hello = get_template_attribute("includes/macros.html.j2","hello")
hello_with_name = get_template_attribute("includes/macros.html.j2","hello_with_name")
return render_template("index.html", hello=hello,hello_with_name=hello_with_name)
index.html:
{{ hello() }}
{{ hello_with_name("Bob") }}
This solution will allow for adding individual macros to the context while rendering a template or template_string and can even be added to the global context via this method. If anyone knows how to add an entire template full of macros, that'd rock, but this allows the basic needed functionality.

Related

Calling method in Twig, how to avoid the return showing as output

I am calling a method in a pre-existing object from inside a Twig template, after properly authorizing it in policy:
{{ thisEmail.AddCC('me#example.com') }}
My problem is that the object method, which I use to produce a side-effect, not to return any text, returns true, and that leaves a visible "1" in my template output.
How to remove this output? I have this one working:
{{ thisEmail.AddCC('me#example.com')|trim('1') }}
But I feel it's not entirely elegant, and it can only remove that specific result. I would prefer to write something like |nul or |drop and have the filter drop everything, regardless of how much or what kind of stuff it receives as input.
I know how to do it by writing my own Twig extension filters, but my question here is: is there a nice way of achieving this with the core Twig language, un-extended?
If you want a twig statement not to output anything you can use the do tag, e.g.
{% do thisEmail.AddCC('me#example.com') %}
source

Render Jinja Markup in Passed Variables

I am moving my blog over from Jekyll to Flask. In my Jekyll blog I use Liquid includes to process overhead heavy items like youtube videos and images and to ensure uniformity so that they can all be updated in the same place if there's a style or code change to the site.
In Flask is there a way to have the Jinja2 template process Liquid variables in the body of the blog article when it's passed to render_template()?
Example:
#route('/article')
def article():
blog_body = "<h1>My Video</h1>{% include '_media.html' type='youtube' id='a2343lj' %}"
return render_template('home.html.j2', content = blog_body)
And then in home.html.j2:
{% block page_content %}
{{ content }}
{% endblock %}
When testing, the template renders the literal string and does not process the include in the variable. Is there any way to get the Jinja template to render the Liquid syntax in the variable passed to it?
While there does not appear to be any way to render a template string using Jinja2 syntax, there is a workaround. At the time the variable is set, you can process it using render_template_string from Flask.
Example:
from flask import render_template, render_template_string
#route('/article')
def article():
blog_body = render_template_string("<h1>My Video</h1>{% include '_media.html' type='youtube' id='a2343lj' %}")
return render_template('home.html.j2', content = blog_body)
Then at least the variable will be rendered at the time it is set, even if not whenever the template is rendered.

Load extends after blocks

So I have been working with twig now, and I use a function manner to render all of my html. My question is, is there a way to render the blocks (with functions) first, and then the {% extends X %} afterwards?
example:
{% extends 'base.html.twig' %}
{% block body %}
{{ resource('script', 'google.com') }}
{% endblock %}
I would want the resource function to trigger, before the file is extended, in some way.
Reason why:
In the base I define another function which loads a head with a base configuration, it also gives easy options to load certain libraries such as bootstrap etc. But I want the user able to later, externally in a body add more resources and make them pop up in the head instead of in the body. I can give more code if needed but I think this will suffice since this is more a twig question than a php question.

Grav CMS: how to show/hide parts of the page depending on conditions?

The Grav's documentation clearly describes how a whole page or a folder could be hidden from unregistered users. It also describes how a whole page could be seen only by particular user groups.
But what about pieces of a page, let's say, some links or a private info I want to show on some conditions?
Ok, for registered users I found a snippet at Login plugin docs:
{% if grav.user.authenticated %}
content for registered users goes here
{% endif %}
But going wider - how can I show/hide pieces of a particular page depending on some custom logic in PHP code, i.e. not necessarily user related?
I'm thinking about a twig/shortcode plugin, something like:
{% if some.custom.condition.or.PHP.function %}
hidden content goes here
{% endif %}
or
[hidden_if_something] hidden content goes here [/hidden_if_something]
But not sure how exactly this should be implemented. So working examples would be appreciated. Thanks.
There is a recipe in the Grav documentation here. This provides an example of how to render the output of a PHP code result in a twig template.
In the example they create a plugin, and implement a twig extension providing access to a php function. They can then simply call that php function like in a twig template.
{{ example() }}
Following that example, you can implement whatever logic you would like in php, and call the function in a twig if statement.
{% if example() == true %}
your conditional output
{% endif %

Wrap contextual html around a specific twig variable {{ product.name }}

I want to automatically wrap some html, lets say <span data-id=".."> when I call {{ product.name }} in my twig template.
So when in a twig template, I use {{ product.name }}, I want the output to be: <span data-type="product" data-id="8" data-prop="name">My product name</span>. I cannot use twig filters or macros, since I really need the template syntax to be {{ product.name }}, so the end-user (template designer), does not have to care about it.
The reason I need this is because I am building an on-page editting tool for twig templates, so I need to know the contexts of those variables from within HTML.
I have tried to override the Compiler that the Twig_Environment uses, but I cannot seem to alter the output of the twig variable node.
How can I do this?
EDIT
I wanted to mention that I need this to use the {{ product.name }} syntax, since other designers will work with those templates outside of Symfony 2. I want to make almost all twig variables editable in the front-end, so a solution with filters or macros can indeed work, but it kills the usability and readability of the platform I am writing. There is no public API currently in twig that can achieve what I want, that is why I am fiddling with the twig compiler. I do not have the required knowledge of the Twig internals to achieve this. If someone could point me into a direction that would be great!
UPDATE 2
I have found a place where I can achieve what I want. Every GetAttr node is compiled to $this->getAttribute($someContext, "property"). So if I can change the subclass of compiled twig template, I can achieve what I want. By default all twig templates extend from Twig_Template. I want to extend this method.
How can I change the subclass of all compiled twig templates?
UPDATE 3
I've found a way to use my own base class for all compiled twig templates. I can simply set it as an option on the twig environment, see this link. I hope to get it working tomorrow and I will post a proper answer on how I solved it all together. Not sure how I will handle escaping, since that will happen after the $this->getAttribute() is called.
I think macros are the best candidates for those kind of wrappings.
For example:
main.twig
{% import "macros.twig" as macros %}
{{ macros.display_product(product) }}
macros.twig
{% macro display_product(product) %}
<span data-id="{{ product.id }}" data-prop="name">{{ product.name }}</span>
{% endmacro %}
Context
product:
id: 8
name: My Georgeous Product
Result
<span data-id="8" data-prop="name">My Georgeous Product</span>
See fiddle
I've solved it by wrapping the PrintNode that is created when parsing a VAR_START token (inside the twig parser) with my own EditablePrintNode. In that node I traverse the expression that is compiled by the print node and get the necessary property path and pass that as an argument to a wrapper function around the default twig escape function that is compiled by the PrintNode.
I suggest to write a custom filter. You can find the doc here about how to write and configure in your environment
// an anonymous function
$filter = new Twig_SimpleFilter('my_custom_product_filter', function ($product) {
return '<span data-id="'.$product->getId().'" data-prop="name">'.$product->getName().'</span>';
});
You need to register as described in the doc
then you can use as follow:
{{ myProduct|my_custom_product_filter}}
Hope this help

Resources