【问题标题】:What is the difference between loader.get_template_from_string() and creating a Template?loader.get_template_from_string() 和创建模板有什么区别?
【发布时间】:2012-11-14 16:41:23
【问题描述】:

我一直在研究一种让用户存储他们自己的模板的方法,我知道我将不得不即时创建模板。例如:

>>> from django.template import Template
>>> Template("Testing {{test}}")
<django.template.base.Template object at 0x10c58f990>

但是,当我询问加载模板字符串时,我被建议使用get_template_from_string:

>>> from django.template import loader
>>> loader.get_template_from_string("Testing {{test}}")
<django.template.base.Template object at 0x10c8b5450>

这两种方法有什么区别?一种方式更pythonic,还是更喜欢另一种方式?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    Django documentation for the templating code 描述了使用您描述的第一种方法:使用Template()。

    它没有提及get_template_from_string,文档中的其他任何地方也没有提及。

    因此,我会严重依赖第一种方法的使用,因为另一种可能在未来更有可能发生变化,因为它是一个未记录的函数。

    【讨论】:

      【解决方案2】:

      在当前版本的 Django 中,get_template_from_string 只是以与您相同的方式实例化一个新模板。

      def get_template_from_string(source, origin=None, name=None):
      """
      Returns a compiled Template object for the given template code,
      handling template inheritance recursively.
      """
          return Template(source, origin, name)
      

      源码在这里:https://github.com/django/django/blob/master/django/template/loader.py

      【讨论】:

      • 虽然知道源只是返回一个模板很有帮助,但我一直在寻找答案,并解释为什么会这样:/
      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2018-06-11
      • 2011-08-26
      相关资源
      最近更新 更多