FAQ Database Discussion Community


ansible jinja2 concatenate IP addresses

jinja2,ansible,ansible-playbook
I would like to cocatenate a group of ips into a string. example ip1:2181,ip2:2181,ip3:2181,etc {% for host in groups['zookeeper'] %} {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }} {% endfor %} I have the above code, but can't seem to quite figure out how to concatenate into a string. searching for "Jinja2 concatenate" doesn't give...

Django Rest + Jinja2: ValueError: dictionary update sequence element #0 has length 0; 2 is required

python,django,rest,django-rest-framework,jinja2
I am currently developing a Django website using the Jinja2 template engine using the django-jinja package. As the website will need a JSON api I thought of using the Django Rest Framework (DRF). Everything worked nicely before using DRF, using class based views that inherited from django's class based views...

Ansible write variables into YAML file

python,yaml,jinja2,ansible
I have a specific ansible variable structure that I want to get from the vault into a yaml file on my hosts. Lets assume a structure like this: secrets: psp1: username: this password: that secret_key: 123 ... I need something like a "generic" template to output whatever "secrets" contains at...

Remove the empty lines left by Jinja2 variable definitions

jinja2,salt-stack
When writing template files using Jinja2 for Saltstack, I often define some variables at the beginning of the file. For example: {% set ip = grains['ip4_interfaces']['eth1'][0] %} {% set domain = pillar['company_domain'] %} {% set version = pillar['site_version'] %} {% set site_url = 'www.' + domain %} [...] Everything works...

Using a context processor in conjunction with Jinja template variables

python,unicode,flask,jinja2
I am in the midst of deploying Stripe and it requires that that payment values being passed into it are stated in "cents" rather than dollars. I can handle this on the backend (i.e I can process a payment for the appropriate amount) but in order to render properly in...

How to round to zero decimals if there is no decimal value with Jinja2?

python,templates,flask,rounding,jinja2
I building a website using the (excellent) Flask framework in which I now want to display some numbers. The round filter provided by jinja2 works fine, except for when there is no decimal value: {{ 1.55555|round(2) }} -> 1.56 {{ 1.5|round(2) }} -> 1.5 {{ 1.0|round(2) }} -> 1.0 {{...

how to iterate over a list of list in jinja

jinja2,jinja
I have a list of list like : [[elem0, elem1, elem2], [elem3, elem4, elem5], [elem6, elem7, elem8], ...] I wrote the follow template file : {% for result in results %} <tr> <td>result[0]</td> <td>result[1]</td> <td>result[2]</td> </tr> {% endfor %} But it didn't work, What i can think is use nested...

Join two tables and show all combinations

python,flask,sqlalchemy,jinja2,flask-sqlalchemy
I have two models: Company and Contact. A Company can have many Contacts. class Company(db.Model): __tablename__ = 'company' id = db.Column(db.Integer, primary_key=True) companyname = db.Column(db.String()) contacts = db.relationship('Contact', backref='contact', lazy='dynamic') def __init__(self, companyname): self.companyname = companyname def __repr__(self): return '<id {}>'.format(self.id) def company_contacts(self): return Contact.query.join(id = Contact.company_id) class Contact(db.Model): __tablename__...

If jinja markup is in string format, how do I use it in django and jinja2?

python,django,jinja2
Part 1 of this question asked and answered separately. I have a Report and a ReportTemplate. +----+----------+---------------+-------------+ | id | title | data | template_id | +----+----------+---------------+-------------+ | 1 | report 1 | {data: [...]} | 1 | +----+----------+---------------+-------------+ reports table +----+-----------+---------------+------------+ | id | title | markup | css...

Create content snippet with Jinja filter

python,flask,beautifulsoup,jinja2
I want to create content snippets for my home page. An example post looks something like <p>Your favorite Harry Potter characters enter the Game of Thrones universe, and you'll never guess what happens!</p> <readmore/> <p>...they all die</p> On the home page I only want the things before <readmore/> to show...

Jinja2 - string variable with a space not reading correctly in classname

flask,jinja2
I'm having an issue with Jinja2 not rendering the string 'fa fa-tachometer' correctly into the class name. Jinja2 renders that string like this: <i class={{ icon }}></i> into <i class="fa" fa-tachometer></i>, as shown in the image below the code. I've done space literals but it doesn't fix the problem for...

Jinja2 for loop in javascript on a list not working but accessing individual elements works

javascript,python,flask,jinja2
I am working on a flask + jinja2 website which involves plotting some stored markers on a map. Python code resultroute['checkpointlist'] = CheckPoint.query.filter_by(route_id=route.code) return render_template('routes/edit.html',route=resultroute) Javascript in edit.html function addExistingMarkers() { //Individual access to elements var name0 = '{{route.checkpointlist[0].name}}'; var lat0 = {{route.checkpointlist[0].latitude}}; var long0 = {{route.checkpointlist[0].longitude}}; var marker =...

How to get an associated model via a custom admin action in Django?

python,django,jinja2
Part 2 of this question asked and answered separately. I have a Report and a ReportTemplate. +----+----------+---------------+-------------+ | id | title | data | template_id | +----+----------+---------------+-------------+ | 1 | report 1 | {data: [...]} | 1 | +----+----------+---------------+-------------+ reports table +----+-----------+---------------+------------+ | id | title | markup | css...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2
I want to create an HTML option list and display it multiple times on the template page. I tried to iterate through the list passed on to the template but this seems only to work once on the page: {% for item in points %} <option value="{{ item }}">{{ item...

Returning Data from Python Function for use with Jinja2 Template (Flask)

python,flask,jinja2
I'm doing my best to learn Python, and I think I'm coming along ok, but I'm stuck here. I am pulling data from the OMDB API. I want the data returned to populate a template for a site I'm making with Flask. So far I'm getting data back from the...

Structuring jinja/flask templates with multiple child templates?

python,design,flask,jinja2
I'm looking to design a site that provides different views of data from a database. I'm new to jinja/flask and templating in general, so it's quite likely I am going about this the wrong way and I'm looking for some feedback or "lordy lord no, you don't ever do that"...

Rendering Jinja template in Flask following ajax response

javascript,python,ajax,flask,jinja2
This is my first dive into Flask + Jinja, but I've used HandlebarsJS a lot in the past, so I know this is possible but I'm not sure how to pull this off with Flask: I'm building an app: a user enters a string, which is processed via python script,...

Sphinx - use custom Jinja2 ChoiceLoader to load templates in specific order

python,jinja2,python-sphinx
My problem is that I need to load jinja2 templates from a python package that I'm sharing across other repos and applications. My local sphinx theme templates will be extending these shared templates. In flask I did something like this # Load common templates template_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.PackageLoader('my_shared_templates', 'templates')...

Is a this a typo in this Jinja2 example, or am I missing something?

flask,jinja2
<p> Please enter your OpenID, or select one of the providers below:<br> {{ form.openid(size=80) }} {% for error in form.openid.errors %} <span style="color: red;">[{{error}}]</span> {% endfor %}<br> |{% for pr in providers %} <a href="javascript:set_openid('{{ pr.url }}', '{{ pr.name }}');">{{ pr.name }}</a> | {% endfor %} </p> I'm going through...

Error while trying to use pyramid_webassets and pyramid_jinja2 together

python,jinja2,pyramid,webassets
I am trying to get my pyramid app to use pyramid_jinja2 and pyramid_webassets. My main config function looks a little like this: def main(global_config, **settings): engine = engine_from_config(settings, 'sqlalchemy.', encoding='utf-8') get_root = appmaker(engine) session_factory = session_factory_from_settings(settings) config = Configurator(settings=settings, root_factory=get_root) config.include('pyramid_handlers') config.include('pyramid_jinja2') config.add_jinja2_renderer('.html') config.add_jinja2_search_path('myapp:templates',...

Jinja2 for word templating

python,jinja2,template-engine,docx
I would like to use jinja2 for word templating like mentioned is this short article. The problem I'm facing is as follows, if I put {{title}} in my word-file the resulting xml can look like this: <w:r><w:t>{{</w:t></w:r><w:proofErr w:type="gramStart"/><w:r><w:t>title</w:t></w:r><w:proofErr w:type="gramEnd"/><w:r><w:t>}}</w:t></w:r></w:p> so it is impossible for jinja to replace this accordingly. Is...

Confirmation modal for flask not working in a loop

python,flask,jinja2
My program lists a set of users that can be deleted. And upon deleting, there'll be a confirmation modal before it deletes the user. The deleting part of the code works, but I have problem with the modal itself because it's the one that passes of the data in the...

Jinja2 - Override block tag inside include?

python,flask,jinja2
Having trouble overriding a block tag inside my include. I have base.html <div> {% include 'snippet.html' %} </div> snippet.html <h1>{% block h1 %}{% endblock h1 %}</h1> index.html {% extends 'base.html' %} {% block h1 %}Hello World{% endblock h1 %} I'd expect it to render as: <div> <h1>Hello World</h1> </div> But...

Show modal on form validation success

html,bootstrap,jinja2,bootstrap-modal,flask-wtforms
I'm trying to launch a modal if my flask-wtf form validation fails. The code snippet below otherwise works as expected other than it launches the modal even when I load the form before submission (appears that form.errors initialises to False before form is submitted). What do I need to change...

Syntax error, unrecognized expression for jquery class selector

jquery,flask,jinja2
I am using jquery 1.11.1 with Flask/jinja2 templates While attempting to remove row based on class, I used $("table#success tr[class=" + sale_id.rowclass +"]").remove(); The "sale_id.rowclass" variable is passed in from my jinja template. When the variable is single valued(eg."n133") the statement works perfectly however when the variable holds a double...

Flask + Jinja and POST/GET variables

python,flask,jinja2
How can I use Jinja2 and Flask to get the hidden variable in this code: <form action="reservation" method="post" name="reservation"> <td><button type="button" class="btn btn-primary">Reservation</button></td> <input type="hidden" name="id" value="{{ d[0] }} "> </form> It would be better may be to use GET but I am stuck with this also....

Flask and Jinja2 url_for error - concatenating json object into url_for

python,flask,jinja2,mapbox
I am using Flask with Jinja2 and MapBox on a project which involves plotting data on a map using GeoJSON derived from model data. Example of how this is loaded: $.getJSON("{{ url_for(".geojson") }}", function(data) { var geojson = L.geoJson(data, { onEachFeature: function (feature, layer) { //do stuff } }); markers.addLayer(geojson);...

Python Google App Engine. GET Request sent twice

python,google-app-engine,jinja2,blobstore,webapp2
A GET Request is being sent twice when a User clicks a link in a Google App Engine, Python App. The App uses webapp2 and jinja2. This only happens if a Blobstore image is missing from the Datastore Model, "Event". If the image is present in "Event", there is only...

How to get data from a form to jinja2

python,flask,jinja2
I am trying to get a value inputted through a form and then back into my jinja template. Which I know doesn't make sense so I guess I am asking how do I go about doing what I want?. Here is what I have: Python @app.route('/test', methods=['GET', 'POST'] ) def...

How to make jinja 2 display different divs if different options are selected [closed]

python,flask,jinja2
{% extends "main.html" %} {% block content %} <h2> Please select a sector you would like to iterate through:</h2> <br /> <form method="POST" action=""> <input type="text" name="statement" /> <input type="submit" /> Do you wish the output to be sorted?: <select> <option value="yes">Yes</option> <option value="no">No</option> </select> </form> {% if request.args.get['yes'] %}...

Best practice for nested menus in Jinja2 Templates

python,jinja2,cherrypy
I am trying to find the best way to generate a nested menu with unordered lists in a Jinga2 template. So far it is working OK but I cannot find a good way to set the active links as the parent and sub item needs to belong to a active...

db.Model.all() returns an empty list

html,python-2.7,google-app-engine,gae-datastore,jinja2
This is a fragment of my tips.html template, included in index.html: {% for t in tips %} <div class="col-lg-4 col-sm-6"> <form action="comment.html" method="get" class="portfolio-box"> <img src="img/portfolio/4.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> {{ t.title }} </div> <div class="project-name"> {{ t.content }} </div> <div><br /></div> {% if user...

How to use Erlang configuration files with Python J2 template?

python,jinja2,ansible
I would like to deploy with Ansible some configuration files the following way: - name: Deploying test configuration template: src={{ item }}.j2 dest={{ basho_bench_home_dir }}/conf/{{ item }} sudo: yes with_items: - http_fix_1min.conf.template - http_max_1min.conf The files have lines like these: {mode, max}. {duration, 1}. {concurrent, 32}. This ultimately breaks the...

Access a layout template from a bluprint template folder

python,flask,jinja2
I have a blueprint with its own template folder. There is also a base layout template in the "top" templates folder. I want to access this template from a blueprint template. I tried the following but got a "Template Not Found" error. {% extends "../../../../../templates/layout.j2" %} The package looks like...

How to remove T from time format %Y-%m-%dT%H:%M:%S?

python,python-2.7,datetime,jinja2
How to remove T from time format %Y-%m-%dT%H:%M:%S in python? Am using it in my html as <b>Start:{{ start.date_start }}<br/> ...

ImportError: cannot import name is_python_keyword

python,jinja2
I am trying to execute a python script , but I get an error on line from jinja2.utils import Markup, concat, escape, is_python_keyword, next ImportError: cannot import name is_python_keyword I checked there is no file named is_python.py...

Jinja 2 Templates: how I check in an if statement whether the boolean is False or None

python,jinja2
So I want to show in a jinja2 template whether a state is True, False or None. Naturally I use a boolean since I have there the three states I need. So I tried the following code to show the True and the False state and wanted to show nothing...

Jinja 2 filesize formatter

google-app-engine,jinja2
I have Jinja2 2.7.3 installed and trying to render a list of files with their filesize. When I use just the parameter vale I get: #using {{fs}} 22528 23786 9769 If I apply the filesizeformatter the outputs are 0 #using {{fs|filesizeformat}} 0.0 kB 0.0 kB 0.0 kB Any idea on...

Case statement for setting var in Ansible/Jinja2

jinja2,ansible,ansible-playbook
I'm using Ansible with Jinja2 templates, and this is a scenario that I can't find a solution for in Ansible's documentation or googling around for Jinja2 examples. Here's the logic that I want to achieve in Ansible: if {{ existing_ansible_var }} == "string1" new_ansible_var = "a" else if {{ existing_ansible_var...

Jinja2 : declaring and saving array

arrays,variables,jinja2
I am new to Jinja2 and I was forced to use it for a custom web application. I want to declare an array and save values to it. Can someone suggest me where I am going wrong? {%- for row in doc.other_charges -%} {%- if not row.included_in_print_rate -%} {% set...

Cherrypy symple dynamic html

python,html,jinja2,cherrypy
I have a very simple query and I apologies, but I have been stuck without being able find the answer for a while. In the script bellow I am trying to "dynamically" create a url using some variable url1 and url2 generated by python further down. I have tried with...

How to use Bootstrap Javascript from Flask-Bootstrap

python,twitter-bootstrap,flask,jinja2
I am using Flask-Bootstrap. I add {% extends "bootstrap/base.html" %} to my template to format it using Bootstrap. How can I use the javascript buttons with bootstrap, since I don't have the js files in my static folder?...

How to pass argument from template to view in Flask

flask,jinja2
I have template which is doing some operations on fields of table: <tr> {% for field in row %} {% if field is link_field %} <td><a href="{{ url_for('munin') }}">{{ field | table_field | safe }}</a></td> {% else %} <td>{{ field | table_field | safe }}</td> {% endif %} {% endfor...

Unusual behavior of jinja2 template_filter decorator in flask application

python-2.7,flask,jinja2,pygit2
I have a filters.py file in my flask application and its content is: # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, print_function import arrow from fresque import APP @APP.template_filter('short') def shorted_commit(cid): """Gets short version of the commit id""" return cid[:6] @APP.template_filter('humanize') def humanize_date(date): """ Template filter returning the...

How to import Python modules for user in Jinja2 template

datetime,jinja2,ansible,ansible-playbook
I want to create a file name by formatting datetime.now(). It is simple enough in Python, but the datetime module needs to be imported. How can I import it for use in a Jinja2 template? For example, in this Ansible task: - name: myTask shell: echo "123" > /tmp/{{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}}.zaz ...

Render Dictionary or String with Jinja2

python,dictionary,jinja2,cherrypy
I've been trying to render a html template with a python dictionary. Actually I created a sitemap for my webpage and implemented it with the {{%extends%}} tag. The solution I wanted to reach is to create a dictionary for each website which can be reached with CherryPy and render it...

Method similiar to 'startswith' in Jinja2/Flask

flask,jinja2
I'm looking for method/way which is similar to python's startswith. What I would like to do is link some fields in table which start with "i-". My steps: I have created filter, which return True/False: @app.template_filter('startswith') def starts_with(field): if field.startswith("i-"): return True return False then linked it to template: {%...

Set flag in Jinja2 loop, access outside of loop [duplicate]

python,jinja2
This question already has an answer here: Jinja2: Change the value of a variable inside a loop 2 answers I would like to set a flag inside a Jinja2 template for loop and later display something or not depending on the flag like so: {% set foobar = False...

I am working on small project with Google AppEngine (Python), tutored by Udacity. I am unable to render user comments to main page

python-2.7,google-app-engine,gae-datastore,jinja2
I am suppose to add forms to my HTML to allow users to add data (comments to my page) and also store the data via GAE-Datastore. I have been able to store the data but not able to get the user comments posted to the main page. Seperate code files:...

Flask/SQLalchemy/Jinja2 — nested loop rendering

python,flask,jinja2,flask-sqlalchemy
I am a beginner to Flask. I am building a simple quiz application. I have two tables. One is question table and the other is options table with one right answer. I wanted to show one question and four options, then second question and so on. I searched every where...

Any way to use jinja2 and flask form instead of ajax and jquery or both?

jquery,python,flask,jinja2
I am wondering if there is a better way to do this. Right now I have jquery parsing over and selecting the active div of each row and sending via ajax the flask route. I was wondering if there was a way to do the same thing via jinja2 with...

render jinja2 template without a Flask context

python,flask,jinja2
I have a Flask application that calls flask.render_template without problems when it is invoked from a flask http request. I need the same method to work outside of flask (from a python back end program) resolved_template = render_template(template_relative_path, **kwargs) I could use the jinja2 api, but I would like the...

Flask Templates couldn't load css

python,css,flask,jinja2
I followed this tutorial for develop templates with flask http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates My file tree is the next one: /static /js bootstrap.min.js jquery_1.11.3.js /css bootstrap.min.css /images /templates index.html /python_venv server.py server.py code: @app.route('/subdomain/') def getPrevisionPoblacion(): return render_template('index.html') And css link inside index.html code is the following: <script src="/static/js/bootstrap.min.js"></script> <link rel="stylesheet"...

Django messages framework with built-in Jinja2 backend

django,jinja2,django-messages
How can I use the Django messages framework with Jinja2 and the built-in Jinja2 backend in Django 1.8? I tried doing it as before, but then remembered that the Jinja2 backend doesn't have the context processors of Django Templating Language. Is it possible via the request as with session. I...

Highlight menu item based on current view

python,flask,jinja2
I'm currently checking a variable in the template on each menu item to see if I should add a CSS class to highlight it. {% if title == "Home" %} <li class="active"> {% else %} <li> {% endif %} I want to create a list containing four menu items. To...

Build a dynamic command from hosts in Ansible

solr,command,jinja2,zookeeper,ansible
I am working on an Ansible deploy script to connect a solr node to a running zookeeper ensemble. The command to link the solr config to zookeeper looks like this: solr/scripts/cloud-scripts/zkcli.sh -zkhost 33.33.33.30:2181,33.33.33.31:2181,33.33.33.32:2181 -cmd upconfig -confdir solr/solr/collection1/conf -confname solr_config I want to make the command as dynamic as possible -...

Jinja2 template variable proper usage syntax

flask,jinja2
I am trying to iterate a list to populate a variable to be used to set the value of a hidden field. See my code example below. I am able to iterate the list and concatenate the variable however, when I go to assign the contents of the variable to...

Is it possible to use Angular with the Jinja2 template engine?

python,angularjs,flask,jinja2
I have a Flask site and I want to use the Angular JavaScript framework. Unfortunately, it seems as if the delimiters overlap. How do I use Angular with Jinja2 if both rely on double curly braces ({{ expr }})? Is it even possible?...

Jinja2/Flask dynamic variable name change

flask,jinja2
I have a Flask method and index.html snippet with a jinja2 for loop def recommendations(): return render_template("index.html", score1='46', score2='12', score3='15', score4='33') index.html: {% for i in range(1,5) %} <p> Your score: {{ score1 }}</p> {% endfor %} How do I dynamically change the names of the score variable based on...

Using Google App Engine Property's verbose_name in jinja2

python,google-app-engine,jinja2,webapp2
I am developing a simple web application with Google App Engine and I'd like to understand how to use the verbose_name option on Properties correctly. I have a simple model: from google.appengine.ext import ndb class Person(ndb.Model): name = ndb.StringProperty(required=True, verbose_name='my_name') surname = ndb.StringProperty(required=True, verbose_name='my_surname') Then I have a very simple...

How do I pass multiple variables from one handler to another in GAE?

python-2.7,google-app-engine,jinja2,webapp2
I want to redirect users to a confirmation page that will display both subject and content (if there is any) if they enter a valid subject, but stay on the same page and display an error if the subject is either blank or over three hundred characters. Here is my...

default value for dictionary in jinja2 (ansible)

jinja2,ansible
jinja2 has filter '|default()' to works with undefined variables. But it does not work with dictionary values. if D may have or not have key foo (D[foo]), than: {{ D[foo]|default ('no foo') }} will prints 'no foo' if D is undefined, but will cause error ('dict object' has no attribute...

ansible can't get inventory_hostname

jinja2,ansible,ansible-playbook
I'm trying to get the short name of a server being worked on. I have this in jinja2: ServerAlias graphite.{{ hostvars[inventory_hostname] }} ServerAlias graphite.{{ hostvars[inventory_hostname] }}.{{dc}}.{{subnet}} The above just spills the whole glob of facts instead of just the short name. This is what the hosts.yaml looks like: graphite.experimental.com dc=lv1...

Jinja2 filter for URL pattern generation in flask views

python,flask,jinja2
I am developing a small Flask application to present data about Cinema. Each cinema has two categories associated with itself Language - language of that cinema. E.g. English, French Genre - E.g. Action, Comedy, Suspense User Case - There is a Cinema named Inception which is in English language and...

Iterating through a nested FormField

python,flask,jinja2,wtforms,flask-wtforms
I'm trying to iterate through a FormField in a Formfield, which are both part of a FieldList. In my views.py I'm calling for the mainForm, the template iterates successfully through the FormField subForm. However, when I can't get the iteration through the subSubForm to work. Those fields never appear in...

Pass values from backend to frontend in polymer

python,google-app-engine,polymer,jinja2,template-engine
I am building a web app using Google App Engine and Polymer. Before using polymer I used to pass my values to the frontend using jinja2 templating: def render_str(self, template, **params): t = JINJA_ENV.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw))) - {% for note in notes %} <div...

jinja2 in python does not print data to template

python,jinja2
Hello I just started using Jinja2 templates in python to build a website but the problem that I face is while printing the template in python console does not print the data to it. And at some point it gives me <built-in method title of str object at 0x7f9adefebe70> Here...

Problems configuring gae_mini_profiler correctly

python,google-app-engine,jinja2
I'm having problems getting https://github.com/Khan/gae_mini_profiler working correctly in my app. I've followed the instructions carefully, and this is my app (with needless stuff stripped out.) import webapp2 from webapp2_extras import jinja2 import appengine_config import handlers import gae_mini_profiler.profiler class MainHandler(handlers.BaseRequestHandler): def get(self): user = separate_file.get_user_and_logins(self) templateid = 'home.html' context = {...

jinja2: sort dict by defined key order?

python,html,django,jinja2,jinja
So lets say I want to display some data like this: • b is foo • a is bar • c is baz ...but my dataset looks like this (or any other order, since JSON doesn't care): { "a": "bar", "b": "foo", "c": "baz" } How do I tell Jinja2...

Load jinja2 templates dynamically on a Pyramid view

jinja2,pyramid
I'm developing a Pyramid project with jinja2 templating engine. Following the jinja2 documentation I've find out a way to load different templates from a unique view. But taking into account that the module pyramid_jinja2 was already configured in my app with a default path for templates. I was wondering if...

Split string into list in jinja?

python,jinja2
I have some variables in a jinja2 template which are strings seperated by a ';'. I need to use these strings separately in the code. i.e. the variable is variable1 = "green;blue" {% list1 = {{ variable1 }}.split(';') %} The grass is {{ list1[0] }} and the boat is {{...

Jinja2 template compilation information

python,jinja2,template-engine,mako
In mako template engine there is a handy ModuleInfo class: class ModuleInfo(object): """Stores information about a module currently loaded into memory, provides reverse lookups of template source, module source code based on a module's identifier. """ Basically, it provides a template source code map, that can help with measuring the...

how do I set a list item by index in jinja2

python,jinja2
hello I want to set the value of an item in a list in jinja2, for that I'm trying <code> {% set arr=[0,0,0,0,0,0,0,0] %} {% print arr %} {% set arr[1] = 1 %} {% print arr %} </code> but receive an error message saying: TemplateSyntaxError: expected token '=', got...

Error closing out for loop using Flask/Jinja

python,flask,jinja2
I am using Flask to connect a website to a database in SQLite3. Trying to iterate through table results, I am using the following code, which is based on the Flaskr tutorial (http://flask.pocoo.org/docs/0.10/tutorial/templates/): `{% extends "layout.html" %} {% block body %} <ul class="students"> {% for student in students %} <li>{{...

Trying to override jinja ChoiceReloader in a Pelican Plugin

python,jinja2,pelican
I have a plugin where I am trying to load a my_assets python package before loading the templates from the folder. The error I receive is: CRITICAL: No assets environment configured in Jinja2 environment def foo(generator): self._templates = {} self._templates_path = [] self._templates_path.append(os.path.expanduser(os.path.join(self.theme, 'templates'))) self._templates_path += self.settings['EXTRA_TEMPLATES_PATHS'] theme_path = os.path.dirname(os.path.abspath(__file__))...

Trying to use a access a variable in another scope after render_template() (Flask)?

python,python-2.7,flask,jinja2,wtforms
I'm trying to create a web app that uses a form (WTForms) to take two svn urls and do something/displays them. It will have an update button that if clicked will ONLY display a table with info along with another submit button that does another function (using show=True given to...

Jinja macro doesn't see value passed to render_template

python,flask,jinja2
On certain pages I want my form drop down to be in a specific order and in other pages in a default order. When passing in a specific order from my app, my macro in form.html doesn't seem to see it. dropdown is never used, the template always displays the...

Creating 2 dimensional array in Python Flask application Jinja2 Template

python,arrays,multidimensional-array,flask,jinja2
Within my Flask index.html template I wish to create a 2 dimensional array within a for loop. The for loop works perfectly fine but trying to 'set' an array that's multidimensional is not working. For example, one of the many things I've tried is: {% set matrix = [[] for...

Using Flask data to generate Javascript. Bad idea?

javascript,flask,jinja2
In teaching myself Flask, I have fallen into the habit of doing something like this in some of my templates: <script type="text/javascript"> {% for r in reviews %} $('#{{ r.review_id }}-starrating').raty({readOnly: true, score: {{ r.rating/100 * 5 }} }); {% endfor %} </script> I didn't think twice about it when...

In jinja2, how to include the same template twice but pass in different variables

python,jinja2
In jinja2, I am trying to dynamically create a html document using the template more than once. My python script looks like this: # In my python script env = Environment() env.loader = FileSystemLoader('.') base_template = env.get_template('base_template.html') # each has the actual content and its associated template content1 = ("Hello...

Pelican Plugin - How to add context variables?

python,jinja2,jinja,pelican
I am making a pelican plugin and I'm having trouble adding variables to the templates. For example in my plugin's code: def baz(generator): generator.foo = 'bar' def register(): signals.generator_init.connect(baz) And in my templates I have: <h1>lorem - {{foo}}</h1> And I would expect lorem - bar to show in the <h1>....

How to back these checkboxes by the datastore?

python,database,google-app-engine,jinja2
I want to save checkbox value to a db and use them in google appengine project. my previous question was about storing this to a session. I modified this simple google project by that. but cant get this work. It saves guestbook entries but not checkboxes. here is html: <html>...

Why is my html code not displayed?

html,css,google-chrome,debugging,jinja2
I added a logo image and then the code below, in the header section, is no longer displayed when the html is viewed. The new image seems to overlap the old content. What changes should I make? <!DOCTYPE html> <html dir="ltr" lang="en-IN" class="js"> <head> <link href="/static/css/koolindex_in.css?{{VERSION}}" rel="stylesheet" type="text/css"> <link href="/static/css/common_in2.css?{{VERSION}}"...

Input value attribute not showing full text on search bar

javascript,html5,flask,jinja2
My code is a web application using Flask (python) framework, I have this search bar implemented on HTML5 and I want the text inputted for search to appear on the search bar after the page loads; like this (where {{query}} is a variable passed on by Jinja2): <form class="search-bar search_header"...

Jinja2 templates If condition not working correctly

python,flask,jinja2
I have an if-statement in a Jinja2 template in complete.html, but it doesn't run the right code regardless if the if-condition is True or False. I call a redirect url to another view function which then renders it, carrying the variable that determines the condition of the if-loop. I printed...

Check if checkbox in NOT checked in a Jinja2 template

html,templates,jinja2
In my jinja2 template I have a list of checkboxes. Initially they all should be checked. Then the user can uncheck some of them for filtering out things. <p><input name="name1" type="checkbox" checked /> blabla1 </p> <p><input name="name2" type="checkbox" checked /> blabla2 </p> <p><input name="name3" type="checkbox" checked /> blabla3 </p> <p><input...

Add input fields dynamically with wtforms

python,flask,jinja2,wtforms,flask-wtforms
I'm not quite sure how approach this matter. I hope i get there. For example I have a table full of addresses on a page. The count of these are dynamic (could be 5 or 10 or any other count). And I want the possibility to edit them on one...