代码之家  ›  专栏  ›  技术社区  ›  Shobi

如何在django中编译保存在数据库中的模板

  •  2
  • Shobi  · 技术社区  · 6 年前

    电子邮件模板示例

    <html>
     ....
         Hello {{ Name }},
     ....
    </html>
    

    所以我需要根据我拥有的上下文变量来编译它。就像我们编译Django模板一样,在当前的场景中我如何做到这一点,

    尝试, render_to_string() get_template() templates/ 文件夹。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Shobi    6 年前

    有两种方法:

    1. 使用 from_string() https://docs.djangoproject.com/en/2.1/ref/templates/api/#django.template.Engine.from_string

    2. 直接使用模板对象。

    例子。

        from django.template import Template
    
        template = Template("My name is {{ my_name }}.")
    
        2
  •  2
  •   daemon24    6 年前

    您可以使用django的template.template类

    from django import template
    
    html_template_str = "<html> Hello {{ Name }} </html>"
    
    t = template.Template(html_template_str)
    c = template.Context({'Name':"Name"})
    html = t.render(c)
    

    html格式 将包含呈现的模板html