解析 genshi 模板中 py:match 的相对路径
<py:match path="foo">
<?python
import os
href = select('@href').render()
SOMEWHERE = ... # what file contained the foo tag?
path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
f = file(path,'r')
# (do something interesting with f)
?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>
上面的“某处”应该是什么? 我希望该 href
属性与其中包含 foo
标记的文件相关,就像其他标记上的 href
属性一样。
或者,哪个文件包含 py:match 块? 这不太好,因为它可能与带有 foo
标记的文件位于不同的目录中。
更糟糕的是:我可以提供我正在渲染的文件的路径作为来自 Genshi 外部的上下文参数,但这可能位于与上述两个目录不同的目录中。
<py:match path="foo">
<?python
import os
href = select('@href').render()
SOMEWHERE = ... # what file contained the foo tag?
path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
f = file(path,'r')
# (do something interesting with f)
?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>
What should go as "somewhere" above? I want that href
attribute to be relative to the file with the foo
tag in it, like href
attributes on other tags.
Alternatively, what file contained the py:match block? This is less good because it may be in a different directory from the file with the foo
tag.
Even less good: I could supply the path of the file I'm rendering as a context argument from outside Genshi, but that might be in a different directory from both of the above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要确保驱动程序(即解析输入文件的Python程序)运行在包含
foo
标签的文件的目录中。 否则,您需要将相对路径(即如何从阅读器运行的目录获取到正在读取的文件的目录)作为上下文参数传递给您的Python代码,并将其添加到os .path.join
命令。通过此设置(并使用通过 Fink 包 genshi-py26 在 MacOS X 10.6.3 上安装的 Genshi 0.6),命令
os.getcwd()
返回包含的文件的当前工作目录foo
标签。对于如此复杂的路径构造,我还强烈建议使用
path=os.path.normpath(path)
,因为您可能不希望这些内容在生成的 HTML 代码中泄漏。You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the
foo
tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as a context argument to your Python code and add it to theos.path.join
command.With this setup (and using Genshi 0.6 installed on MacOS X 10.6.3 via the Fink package genshi-py26) the command
os.getcwd()
returns the current working directory of the file containing thefoo
tag.For such complicated path constructs I also strongly recommend to use
path=os.path.normpath(path)
, since you may not want such things to leak in your resulting HTML code.