Kingle
Kingle

Reputation: 345

How do I pass variable to a Jinja template that was not rendered?

I'm writing a flask app for a book with many chapters. On the index page I have links to each chapter as: <a href="/chapters/{{ chapter }}">{{ chapter }}</a>. My function to render each chapter is:

@app.route("/chapters/<chapter>")
def chapter(chapter):
    return render_template(f"chapters/{chapter}.html", chapter=chapter)

I separated the layout of the chapter and the text. So my chapter.html include the layout and have a block for the actual content:

{% include "layout.html" %}

{% block chapter %}{% endblock %}
...

While something like chapter-1.html extends chapter.html and contain the actual text of the book. But now I want to have buttons on chapter.html that allows the user to go to the previous/next chapter. Is there a way for me to pass the chapter variable from the function to the template chapter.html without it being rendered?

Upvotes: 0

Views: 851

Answers (1)

simanacci
simanacci

Reputation: 2344

@app.route("/chapters/<chapter>")
def chapter(chapter):
    session['chapter'] = chapter
    return render_template(f"chapters/{chapter}.html", chapter=chapter)

Use CSS to style an <a> tag so that it looks like a button and store the chapter in sessions.

<a href="{{ url_for( 'chapter', chapter=session['chapter'] - 1) }}" class="button-style">Previuos</a>

and for the next chapter:

<a href="{{ url_for( 'chapter', chapter=session['chapter'] + 1) }}" class="button-style">Next</a>

If your chapter value is a string use chapter=int(session['chapter']).

Upvotes: 1

Related Questions