Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using include to dynamically point to HTML

I want to point to a different HTML files based on a variable. I am using include in the following format:

{% include 'templates/case/{{cid}}/intro.html' %}

This throws an error:

TemplateNotFound: templates/case/{{cid}}/intro.html

Looking at this I know Jinja2 does not resolve the variable at runtime. The value of cid = ABC (ABC is a folder's name in the path), so I expected the total path to be:

templates/case/ABC/intro.html

If I use this resolved path directly in include it works.

How can I resolve this?

like image 802
Utpal Avatar asked Sep 02 '12 06:09

Utpal


4 Answers

At least in Jinja2 2.7.1 this works:

{% include 'templates/case/%s/intro.html' % cid %}
like image 146
fonso Avatar answered Nov 20 '22 01:11

fonso


Here's how to pass the code directly through include

{% include "templates/case/"+cid+"/intro.html" %}
like image 41
kunsam002 Avatar answered Nov 20 '22 03:11

kunsam002


Found the answer in another Stack Overflow question here:

{% set path = 'templates/case/' + cid + '/intro.html' %}{% include path %}
like image 6
user545424 Avatar answered Nov 20 '22 01:11

user545424


You could always compute the full path in view code and pass that down to the template, at that point, remove any quotes and curly braces around the variable.

While doing this, be wary of path traversal attacks.

like image 3
Thomas Orozco Avatar answered Nov 20 '22 01:11

Thomas Orozco