Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include macros / other templates with a FunctionLoader in Jinja2?

Tags:

jinja2

I'm trying to use a sandboxed Jinja2 environment to handle template customizations.

I've tried using both a DictLoader and FunctionLoader, but keep running into similar issues... I'm mostly concerned with FunctionLoader now.

I can't manage to include or import another template (which contains macros). The FuctionLoader's specified "load" function is never called for the referenced templates.

I've tried with no luck:

  • just expecting an import would hit the loader using basic 'import' and 'include' syntax
  • passing the loader into the context , seeing if it might pull in that way
  • passing a dict of templates into the context, also hoping it might pull in
  • a few more things , all of which I forgot

I'm sure there's got to be a way to support this - can someone point me in the right direction ?

like image 212
Jonathan Vanasco Avatar asked Mar 07 '13 21:03

Jonathan Vanasco


People also ask

What are macros in Jinja2?

Macros within Jinja2 are essentially used like functions with Python and are great for repeating configs with identical structures (think interface configurations, ASA object-groups, etc).

What is the difference between Jinja and Jinja2?

from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration. Jinja 1 performed automatic conversion of bytes in a given encoding into unicode objects.


1 Answers

The import syntax must use quoted strings.

Bad:

{% import utils %}
{% import utils.macros as macros %}
{% from utils.macros import macro_1 , macro_2 %}

Good:

{% import "utils" as utils %}
{% import "utils.macros" as macros %}
{% from "utils.macros" import macro_1 , macro_2 %}

The quoted string is passed into the FunctionLoader or used as the key with the DictLoader

like image 82
Jonathan Vanasco Avatar answered Oct 20 '22 18:10

Jonathan Vanasco