How can I render a JS template from a rendered HTML template?

后端 未结 1 1756
独厮守ぢ
独厮守ぢ 2021-01-12 17:42

If I\'d like to generate JavaScript code, and not just HTML, through Jinja2, am I stuck with keeping the JS code inline, or is there a way for me to reference the script?

相关标签:
1条回答
  • 2021-01-12 18:25

    You can add a route that generates the JS.

    @app.route('/script.js')
    def script():
        return render_template('script.js', color='pink')
    

    And in script.js, this should be in the same folder as your other templates:

     function myEnterFunction() {
                    element = document.getElementById("demo");
                    element.style.backgroundColor = "{{ color }}";
                }
    

    And in your layout.html:

    <script src="{{url_for('script')}}"></script>
    

    Jinja2 will parse any files containing it's syntax.

    0 讨论(0)
提交回复
热议问题