【问题标题】:How should I access Cheetah Template() variable placeholders in an object instance?我应该如何访问对象实例中的 Cheetah Template() 变量占位符?
【发布时间】:2021-12-16 14:53:06
【问题描述】:

我正在尝试设置一个对象实例,该实例将为 Cheetah3 文本模板引擎提供值。

这是我的文本模板脚本...

#filename: py_text_template.py

from traits.api import String, Range
from traits.api import HasTraits

from loguru import logger

from Cheetah.Template import Template

class Info(HasTraits):
    keyword_integer = Range(value=0, low=1, high=60)
    keyword_string = String(value="snack", regex=r"^\w+")

@logger.catch(onerror=lambda _: sys.exit(1))
def generate_text_template():
    myinfo = Info(keyword_integer=10, keyword_string="snack-attack")
    t = Template("On the first $myinfo.keyword_string, my true love")
    print(t)

generate_text_template()

我希望使用Info() 类的myinfo 实例来填充Template,但出现以下错误...

Cheetah.NameMapper.NotFound: cannot find 'myinfo'

【问题讨论】:

    标签: python enthought templating-engine cheetah


    【解决方案1】:

    由于我还不明白的原因,Cheetah 不遵循常规约定来访问对象实例属性和方法。

    为了解决这个问题,我不得不将$myinfo.keyword_string 调用替换为$keyword_string。然后我在Template() 通话中添加了searchList=[myinfo]...

    myinfo = Info(keyword_integer=10, keyword_string="snack-attack")
    t = Template("On the first $keyword_string, my true love",
        searchList=[myinfo])
    

    搜索searchList 中的对象实例以查找相关的字典键、属性或方法。

    完整的工作 Cheetah 脚本是:

    #filename: py_text_template.py
    
    from traits.api import String, Range
    from traits.api import HasTraits
    
    from loguru import logger
    
    from Cheetah.Template import Template
    
    class Info(HasTraits):
        keyword_integer = Range(value=0, low=1, high=60)
        keyword_string = String(value="snack", regex=r"^\w+")
    
    @logger.catch(onerror=lambda _: sys.exit(1))
    def generate_text_template():
        myinfo = Info(keyword_integer=10, keyword_string="snack-attack")
        t = Template("On the first $keyword_string, my true love",
                                  # ^^^^^^^^^^^^^^
            searchList=[myinfo])  # <--- put myinfo instance here
        print(t)
    
    generate_text_template()
    

    在 python3.7 下运行会产生预期的结果...

    (py37_test) [mpenning@mudslide fixme]$ python py_text_template.py
    
    On the first snack-attack, my true love
    (py37_test) [mpenning@mudslide fixme]$
    

    此脚本需要安装:

    我正在使用:

    • Linux mudslide 5.10.0-9-amd64 #1 SMP Debian 5.10.70-1 (2021-09-30) x86_64 GNU/Linux
    • Python 3.7.0
    • 特征 6.3.2
    • loguru 0.5.3
    • 猎豹3.2.6.post1

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2016-09-15
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多