Solution 1 :

You can’t call the function text() within your template. Hence the error. What you should do is pass the string returned by the function as a variable to the template.

home.html:

<html>
<body>
  <h2>
    {{text}}
  </h2>
</body>
</html>

app.py:

@app.route('/')
def home():
    txt = text()
    return render_template('home.html', text=txt)

Problem :

How can I return the function text() with it’s output to be viewed in html ?

my home.html in template folder:

<html>
<body>
  <h2>
    {% text() %}
  </h2>
</body>
</html>

my app.py in root folder:

from flask import Flask, render_template
import random

app = Flask(__name__)

def text():
    f = open('motivational.txt','r')
    text = f.readlines()
    return text[random.randrange(0,371)]

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

if __name__ == "__main__":
    app.run(debug=True)

error :

File "~/templates/home.html", line 494, in template
{% text() %}
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'text'.

thanks

By

Leave a Reply

Your email address will not be published. Required fields are marked *