解析 genshi 模板中 py:match 的相对路径

发布于 2024-07-25 07:14:02 字数 697 浏览 4 评论 0原文

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不一样的天空 2024-08-01 07:14:03

您需要确保驱动程序(即解析输入文件的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 the os.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 the foo 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文