如何在网站上的所有页面中包含带有 css 的模板

Posted

技术标签:

【中文标题】如何在网站上的所有页面中包含带有 css 的模板【英文标题】:How to include template with css to all pages on website 【发布时间】:2014-02-03 08:40:36 【问题描述】:

我创建了一个包含页眉、导航和页脚的 template.html,我想将其包含到我的所有其他页面:网站上的 html/php 文件,而无需将所有代码复制到所有其他文件。 是否有捷径可寻?还是有更合适的方法来处理这个? 我已经尝试过使用 php 要求页面,但它没有采用任何样式。

更新:我最终切换到使用包含功能。 我需要在我的 html 中使用 php,如果你回显 php 脚本,代码就会被注释掉。 我发现最好的方法是使用包含头部、页眉(和导航)和页脚。 但是,为了避免制作多个打开和关闭 html 标记,我将其格式化为:

head: <html><head>
-content for head
header: </head><body><header></header>
-content between header and footer
footer: <footer></footer></body></html>

【问题讨论】:

您可以使用 jQuery .load() 函数为您的身体创建一个巨大的 div。不是最优雅的,但最有效。 【参考方案1】:

好吧,你把你的:

一个文件中的标题,例如 header.php 一个文件中的页脚,例如 footer.php 等等。

然后在您的其他 .php 文件中,您只需调用包含函数,给出您的页眉/页脚路径。

【讨论】:

【参考方案2】:

我会组织我的不同脚本,以便它们都从 index.php 中调用(如果尚未完成)。然后,就在构建页面的逻辑之前,我将包含页眉和导航,以及之后的页脚。

这是一个模板:

<!DOCTYPE html>
<html>
<head><!-- here your header --></head>
<body>
~
<!-- here your navigation? -->
~
</body>
</html>

我把那些 '~' 放在能够爆炸的地方:

$template = explode('~',file_get_contents('template.html'))
// that way we have our code in an array we can easily use for header, navig and footer
$html = $template[0]; // header
$html.= $template[1]; // nav

switch($action) 
case 'foo':
  $html.= file_get_contents('foo.html');// just add directly html content
  break;                                // careful that it does not have <body> tags
case 'bar':
  require_once('bar.php');
  $html.= showBar(); // if you have a function in your script, you can add it to your page that way
  break;


$html.= $template[2]; // footer

如果您的其他脚本直接回显内容,请将$html.= 更改为echo

【讨论】:

工作得很好,但是我的 template.html 有一个单独的样式文件 template_style.css(我可以直接将样式复制到 template.html 中),但我也有一个 Spry 可折叠面板没有出现。我应该分别包含 spry 面板中的 .js 和 .css 吗? 我的错误,template.html 被放置在一个单独的文件夹中,这弄乱了对样式表和 spry 面板的引用。

以上是关于如何在网站上的所有页面中包含带有 css 的模板的主要内容,如果未能解决你的问题,请参考以下文章

如何在引导程序 3 中包含字形图标 [重复]

如何在 vimwiki html /smarty 文件中包含 pygments?

如何在Nuxt.js项目的页面中包含CSS

如何在 asp.net 页面中包含外部 html 文件

如何在 document.ready 之后在页面中包含嵌入式 youtube 频道?

在我的 django 模板中包含 CSS 和 Javascript [重复]