Search code examples
pythonflaskjinja2

Flask: Render a dynamic template by clicking HTML button


Let's say I have in a view this html code

<html>
stuff...
{% if thisistrue %}
<p> let me see this </p>
{% endif %}
</html>

I'd like to have thisistrue = True only if I press a button from another view. Otherwise I want it to false.

I tried to use dynamic flask routes and jquery like

@app.route('/mainroute/<param/')
def main(param):
if param:
 return render_template(thisistrue = True)
else:
 return render_template(thisistrue = False)

but I failed since it doesn't fit with my subroutes (like mainroutes/somethingelse/


Solution

  • Use javascript with onclick event (for button) whose href value leads to new_template.html. The content of the new_template.html will be rendered by the python file.

    Edit: The same thing can be done without javascript as well (i.e) using <button href = "/new-template">Submit</button>. But here full page reload will take place and the transition will not be smoother. For the sake of good user experience, the javascript is important.

    Edit-2: Since there was an error again, edited now. Since the variable show_data is passed as an argument along with the url(which is similar to the get request), If we declare just show_data= True, It won't work. Instead, it should be show_data = request.args.get('showData', True)`. Now it is working alright.

    Please no that there is a difference in spelling and case between 'showData' in javascript and show_data in the python script

    HTML with button(index.html)

    <!DOCTYPE html>
    <html>
    <head>
        
    </head>
    <body>
        
        <button id="new_temp">Submit</button>
    
        <script>
            document.getElementById("new_temp").addEventListener("click", function() {
                window.location.href = "/new_template?showData=true";
            });
        </script>
    </body>
    </html>
    

    Python

    from flask import Flask as fl, request as rq
    from flask import render_template as tmp
    
    app = fl(__name__)
    
    @app.route("/")
    def index(): return tmp("index.html")
    
    @app.route("/new_template")
    def new_template():
        show_data = rq.args.get("showData", True)   
        txt = "This is the new template content!"  
        return tmp("new_template.html", data=txt, show_data=show_data)
    
    if __name__ == '__main__': app.run()
    

    HTML (new_template.html):

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
        {% if show_data %}
            <h1>{{ data }}</h1>
        {% endif %}
    </body>
    </html>