Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在模板之间共享代码(“模块”?_Python_Templates_Module_Pylons - Fatal编程技术网

Python 如何在模板之间共享代码(“模块”?

Python 如何在模板之间共享代码(“模块”?,python,templates,module,pylons,Python,Templates,Module,Pylons,如果我的Pylons网站中有两个控制器,它们提供两个不同的模板文件,那么在每个模板上显示相同的HTML片段的最佳方式是什么 例如,假设我有一个博客。首页将显示最近的条目列表,每个条目都有一个“永久链接”,链接到只显示该条目的页面。在每一个页面上,我都想显示“最新条目”——一个包含5篇最新博客文章的列表 模板文件不同。控制器是不同的。如何显示“最新帖子模块” 我应该吃点像这样的东西吗 from blog.model import posts class BlogController(BaseCo

如果我的Pylons网站中有两个控制器,它们提供两个不同的模板文件,那么在每个模板上显示相同的HTML片段的最佳方式是什么

例如,假设我有一个博客。首页将显示最近的条目列表,每个条目都有一个“永久链接”,链接到只显示该条目的页面。在每一个页面上,我都想显示“最新条目”——一个包含5篇最新博客文章的列表

模板文件不同。控制器是不同的。如何显示“最新帖子模块”

我应该吃点像这样的东西吗

from blog.model import posts

class BlogController(BaseController):

    def index(self):
        c.latestPosts = posts.get_latest()

        return render('home.html')

class OtherController(BaseController):

    def index(self):
        c.latestPosts = posts.get_latest()

        return render('otherpage.html')
c.latestPosts
将是模板呈现的链接列表。我看到的问题是,我必须在两个单独的模板文件上呈现HTML。如果我想改变HTML,这意味着在两个地方改变它


我正试图想出一个简洁的方法来做到这一点,但我已经没有主意了。您将如何做到这一点?

能够共享常见的HTML片段,如页眉、页脚、页面的“登录”区域、边栏等,这是一个非常常见的要求。模板引擎通常为此提供方法

如果您正在使用Mako,以下是您可以使用的两种主要机制:

包括 看看标签。在页面模板中,指定各种可重用位的放置位置。您可以从头开始构建页面,使用现有的可重用组件进行组装

Mako文档中的示例:

<%include file="header.html"/>

    hello world

<%include file="footer.html"/>
somepage.mako

<html>
<head></head> 
<body>
    ${self.header()}

    ${self.body()}

</body>
</html>

<%def name="header()">

This is the common header all pages will get unless 
they override this.

</%def>
<%inherit file="/base.mako"/>

This content will go into body of base.

此内容将进入基础正文。

模板引擎通常有很多漂亮的特性,我鼓励你好好了解它们

尽管pēteris的答案很好,但您可能也在寻找与原始Python中的“import”语句非常相似的

然而,和也是你应该经常使用的东西