0

I made a web application with flask. I want to pass a varable value to my template, to set property.

in python:

web_size="100%"

@app.route('/')
def home():
  return render_template("web.html")

def size():
  return "50px"

In the html5 file, I used that:

width: {{url_for('size')}};

what did i wrong? and how can I use orl_for command? I think I didn't even understand how it works.

davidism
  • 121,510
  • 29
  • 395
  • 339
Erik Nagy
  • 31
  • 5

2 Answers2

2

To pass a Python variable to a Flask template do the following:

In the view first declare the Python variable. Then, pass the variable to the template as a parameter in your render_template method:

@app.route('/', methods={'GET'})
def home():
    title = "Frankenstein"
    return render_template('index.html', book_title=title )

Then, to display the variable in your index.html template use curly braces:

<h3>The book named "{{book_title}}" </h3>
Luke
  • 2,751
  • 1
  • 17
  • 20
  • 1
    so in that case visually you make a *gate* between the 2 files? named book_title – Erik Nagy Apr 29 '21 at 16:43
  • I'm not sure "gate" is the technically correct term. But the idea is you declare the variable in the view, you pass that variable to the template in your render_template method, and you reference that variable in your template using the curly braces. The only half-tricky thing is to remember what string to put in the curly braces (in the above example {{book_title}} will render what you want. But {{title}} will not. – Luke Apr 29 '21 at 16:51
1

You haven't passed the data into the html sheet. For example:

message = 'Hello!'
return render_template('index.html', value= message)
olijeffers0n
  • 103
  • 2
  • 6
  • 1
    and if I use it with the previous solution, I can change the value dinamically? (with changing the *message* variable and reload the template) – Erik Nagy Apr 29 '21 at 16:44
  • In my example the view and template will allways display the value "Frankenstein." But if you wanted that to be dynamic you could set the value of the declared variable by accessing the values in the request. Here's a stackoverflow post that discusses one way to do this: https://stackoverflow.com/questions/15182696/multiple-parameters-in-flask-approute – Luke Apr 29 '21 at 17:02