render jinja2 template without a Flask context

烈酒焚心 提交于 2020-01-10 19:26:06

问题


I have a Flask application that calls flask.render_template without problems when it is invoked from a flask http request.

I need the same method to work outside of flask (from a python back end program)

resolved_template =  render_template(template_relative_path, **kwargs)

I could use the jinja2 api, but I would like the same method to work, in both contexts (flask and command line)


回答1:


You need to render it in an app context. Import your app in your backend code and do the following.

with app.app_context():
    data = render_template(path, **context)



回答2:


If you want to completely bypass flask and use purely Jinja for rendering your template, you can do as such

import jinja2

def render_jinja_html(template_loc,file_name,**context):

    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_loc+'/')
    ).get_template(file_name).render(context)

And then you can call this function to render your html




回答3:


What I use is this code:

import jinja2
template_values = {
  'value_name_in_html': value_name_in_python,   
}

template = JINJA_ENVIRONMENT.get_template("file_patch")
self.response.write(template.render(template_values))


来源:https://stackoverflow.com/questions/30382187/render-jinja2-template-without-a-flask-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!