【问题标题】:template lookup issues. What am i not understanding?模板查找问题。我不明白什么?
【发布时间】:2013-04-12 14:16:28
【问题描述】:

背景:

我的目录结构如下:

/absolute/path/to/templates
            components/
                   component1.mak
                   component2.mak
            template1.mak

计划是把模板目录下的模板给include一堆组件。

在 template1.mak 我有类似的东西:

 <%include file="xxx.mak"/>

其中xxxcomponents/component1.mak 或只是component1.mak(我尝试了两种不同的结果,详情如下)

mylookup = TemplateLookup(directories=[yyy,])
oTemplate = Template(filename='/path/to/templates/template1.mak', lookup=mylookup)
oTemplate.render(args)

其中 yyy 是 '/absolute/path/to/templates''/absolute/path/to/templates/components'

问题:

无论我使用 xxx 和 yyy 值的哪种组合,都会出现模板查找异常。 yyy 的值(查找路径)似乎对异常没有任何影响。

如果 xxx(包含标记路径)是 'components\component1.mak',则错误表示找不到文件 /absolute/path/to/templates/components/component1.mak。如果xxx 只是'component1.mak',则错误是找不到/absolute/path/to/templates/component1.mak

问题

如何让 mako 将这些内容包含在 components 目录中?我对模板查找有什么遗漏或不了解?

【问题讨论】:

  • 在模板中定义您的 xxx 调用时,您是否尝试过使用前导 / 进行此操作?或者在你的 python 代码中使用原始字符串?
  • @bdiamante:成功了 :) 将其发布为答案,以便我给你一些积分

标签: python mako python-3.3


【解决方案1】:

在模板中定义您的 xxx 调用时,尝试使用前导 /

【讨论】:

  • 你能分享一个完整的工作示例吗?试图让我的头脑了解 Mako 模板,但这并不是非常简单:)
【解决方案2】:

只是想提供一个更丰富的答案 - 路径实际上取决于执行代码的文件。

示例 1

web/file.cgi              // was called first from the web
web/templates/header.mako // was called somewhere in file.cgi

在这种情况下,查找目录应该是:

mylookup = TemplateLookup(directories=['templates/'])

示例 2

// was called first from the web
web/file.cgi                 

// was imported and called in file.cgi
../somewhere/in-PYTHONPATH/mymodules/modulename.py

// was called from modulename.py
../somewhere/in-PYTHONPATH/mymodules/templates/edit.html 

那么您的查找目录实际上应该是:

 mylookup = TemplateLookup(directories=['../../../../somewhere/in-PYTHONPATH/mymodules/templates/'])
 OR
 mylookup = TemplateLookup(directories=['/fullpath/to/somewhere/in-PYTHONPATH/mymodules/templates/'])

您需要完整路径,因为web/file.cgi 不位于与后端模块的相对路径中...

出于某种原因,Mako Templates 不知道在其调用 mymodules/templates/edit.html 的位置的 mymodules/modulename.py 文件的相对目录中查找不知道为什么(或者它可能只是我的旧版本 Mako 模板)

虽然&lt;%include file="xxx.mak"/&gt; 的行为有所不同,因为它确实会相对于找到文件的位置进行查找,这就是为什么/ 将其拉高一级 - 然后它查看templates/ .. 但是再说一遍,对于服务器中某处的模块,它的工作方式不同......

希望它可以帮助其他人......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 2022-07-28
    相关资源
    最近更新 更多