【问题标题】:Load template from a string instead of from a file从字符串而不是从文件加载模板
【发布时间】:2011-01-11 03:44:40
【问题描述】:

我决定将所有系统电子邮件的模板保存在数据库中。 这些邮件的正文是普通的 django 模板(带有标签)。

这意味着我需要模板引擎从字符串而不是文件加载模板。有没有办法做到这一点?

【问题讨论】:

    标签: django-templates


    【解决方案1】:

    在 >= Django 3 上使用 django Template 和 Context 为我工作。

    from django.template import Template, Context
    
    template = Template('Hello {{name}}.')
    context = Context(dict(name='World'))
    rendered: str = template.render(context)
    

    【讨论】:

      【解决方案2】:

      为了补充来自 Ignacio Vazquez-Abrams 的 the answer,下面是我用来从字符串中获取模板对象的代码 sn-p:

      from django.template import engines, TemplateSyntaxError
      
      def template_from_string(template_string, using=None):
          """
          Convert a string into a template object,
          using a given template engine or using the default backends 
          from settings.TEMPLATES if no engine was specified.
          """
          # This function is based on django.template.loader.get_template, 
          # but uses Engine.from_string instead of Engine.get_template.
          chain = []
          engine_list = engines.all() if using is None else [engines[using]]
          for engine in engine_list:
              try:
                  return engine.from_string(template_string)
              except TemplateSyntaxError as e:
                  chain.append(e)
          raise TemplateSyntaxError(template_string, chain=chain)
      

      engine.from_string 方法将使用settings.TEMPLATES 的第一个后端实例化一个django.template.Template 对象,并将template_string 作为其第一个参数,不会导致错误。

      【讨论】:

      • 如果您可以将上下文传递给它,我会喜欢这个答案
      【解决方案3】:

      实例化一个django.template.Template(),传递字符串以用作模板。

      【讨论】:

      • 这不会使用settings.TEMPLATES['BACKEND']中配置的后端,而是始终使用Django的模板系统。有没有办法从配置后端的字符串创建模板?
      • 从设置中获取后端,查找要使用的 Template()(具有映射或内省)并实例化它。
      猜你喜欢
      • 2016-04-10
      • 2017-01-15
      • 2012-03-16
      • 2013-01-29
      • 2011-02-21
      • 2011-09-09
      • 2012-01-25
      • 2015-02-24
      • 2013-07-03
      相关资源
      最近更新 更多