Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert static files literally into Jinja templates without parsing them

Tags:

python

jinja2

I'm trying to insert file into a page using Jinja 2.6 using the include tag. This worked fine until I started using characters in the file that are reminiscent of the Jinja syntax, at which point it realized it couldn't parse them and bombed.

Short of going though the file and escaping all characters, what can I do to tell Jinja to just include the file as is?

like image 388
Sudhir Jonathan Avatar asked Mar 19 '12 09:03

Sudhir Jonathan


People also ask

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.

What is Autoescape in Jinja?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.

What is a Jinja2 macro?

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).


1 Answers

You can define a function to load the text file and render it in the template:

import jinja2

def include_file(name):
    return jinja2.Markup(loader.get_source(env, name)[0])

loader = jinja2.PackageLoader(__name__, 'templates')
env = jinja2.Environment(loader=loader)
env.globals['include_file'] = include_file

def render():
    return env.get_template('page.html').render()

if __name__ == '__main__':
    print render()

In the template, call it like this:

{{ include_file('file.txt') }}
like image 62
Alex Morega Avatar answered Sep 21 '22 12:09

Alex Morega