Python 模板查找问题。我不明白什么?

Python 模板查找问题。我不明白什么?,python,mako,python-3.3,Python,Mako,Python 3.3,背景: 我有以下目录结构: /absolute/path/to/templates components/ component1.mak component2.mak template1.mak 计划是让模板目录中的模板包含一组组件 在template1.mak中,我有如下内容: <%include file="xxx.mak"/> 其中yyy是'/abs

背景:

我有以下目录结构:

/absolute/path/to/templates
            components/
                   component1.mak
                   component2.mak
            template1.mak
计划是让模板目录中的模板
包含一组组件

在template1.mak中,我有如下内容:

 <%include file="xxx.mak"/>
其中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调用时,尝试在前面加一个
/

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

例1 在这种情况下,查找目录应为:

mylookup = TemplateLookup(directories=['templates/'])
例2 那么您的查找目录实际上应该是:

 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 Templates)

虽然
的行为有所不同,因为它查找文件的相对位置,这就是为什么
/
将其提升一级,然后查看
模板/
。。但是,对于服务器中的某个模块,它的工作方式也不一样


希望它能帮助其他人…

在模板中定义xxx调用时,您是否尝试过使用前导的
/
?或者在python代码中使用原始字符串?@bdiamante:这就是诀窍:)将其作为答案发布,这样我就可以给你一些要点,你可以分享一个完整的工作示例吗?试着了解Mako模板,但这并不简单:)
mylookup = TemplateLookup(directories=['templates/'])
// 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/'])