0

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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.