Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare python variables within flask templates?

I've got some basic experience building websites using a LAMP stack. I've also got some experience with data processing using Python. I'm trying to get a grip on the mongodb-flask-python thing, so I fired everything up using this boilerplate: https://github.com/hansonkd/FlaskBootstrapSecurity

All is well.

To experiment, I tried declaring a variable and printing it...

I get this error message:

TemplateSyntaxError: Encountered unknown tag 'x'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

Here's my main index.html page

{% extends "base.html" %}


{% block content %}

    <div class="row">
        <div class="col-xs-12">
            Hello World, at {{ now }}, {{ now|time_ago }}
        </div>
    </div>
    <div class="row-center">
        <div class="col">
            {% x = [0,1,2,3,4,5] %}
            {% for number in x}
            <li> {% print(number) %}
            {% endfor %}
        </div>
    </div>

{% endblock %}

I love learning new things, but man, can I ever get hung up for hours on the simplest of things... any help would be greatly appreciated!!!

like image 466
FLAV10 Avatar asked Sep 18 '17 23:09

FLAV10


Video Answer


2 Answers

Flask uses Jinja as its default templating engine.

The templating language is python-esque, but is not python. This is different from something like a phtml file, which is php interspersed with html.

Check the jinja documentation for more of what you can do, but here's how you set a variable within a template:

{% set x = [0,1,2,3,4,5] %}

http://jinja.pocoo.org/docs/2.9/templates/#assignments

like image 115
alexbclay Avatar answered Oct 23 '22 12:10

alexbclay


Try this:

{% set x = [0,1,2,3,4,5] %}

See Jinja docs.

like image 37
Abe Avatar answered Oct 23 '22 12:10

Abe