【问题标题】:Add extra scripts to a page with header.php include file?使用 header.php 包含文件向页面添加额外的脚本?
【发布时间】:2014-12-02 16:42:56
【问题描述】:

我正在尝试将 doctype、head、scripts 等以及打开 body 标记移动到 header.php 包含文件。我正在为页面标题等设置 php 变量。

所有页面都使用相同的脚本,但需要额外脚本的页面除外。

我不知道该怎么做?

如何向使用页眉模板的页面添加额外的标签?

感谢您的帮助!

【问题讨论】:

  • 与其有条件地在标题中包含那个额外的脚本,为什么不把它包含在你需要它的一页上呢?
  • header.php 扩展至开始的正文标记。如果我只是将它包含在该页面上,它就不会出现在 head 部分?
  • 为什么一定要放在头上?
  • 因为代码强迫症:)
  • 好吧,抛开强迫症不谈,你不应该在头脑中加载脚本。最好将脚本加载到尽可能靠近页面底部的位置(通常在结束 body 标记之前)。重要的脚本除外,例如 jQuery。

标签: php html


【解决方案1】:

最简单的解决方案:

需要额外位的脚本:

$show_extra = TRUE;
include('header.php');

header.php

<html>
<head>
if (isset($show_extra) && ($show_extra)) {
   ... output extra bits
}
</head>
etc...

【讨论】:

  • 无法工作 - maps.googleapis.com/maps/api/js"></script> } ?> script 标签周围有什么括号?
  • 您的 php.ini 中直接有 html。这是一个语法错误。你需要回显脚本,或者&lt;? if(...) { ?&gt;&lt;script&gt;...&lt;/script&gt;&lt;?php } ?&gt;
  • 谢谢,在您的帮助下,我现在已经修复了代码。一切正常:)
【解决方案2】:

你可以有一个 header($array_scripts) 函数,它显示你的标题和里面的所有脚本。

假设你的脚本是 CSS 文件,你的文件是这样组织的:

/www
---- /css
     ---- script1.css
     ---- script2.css
---- index.php
---- header.php

在您的页面 index.php 上:

include_once("header.php");
$scripts = array("script1.css", "script2.css");
header($scripts);
// Rest of the code : <body>

在你的 header.php 文件中:

 function header($array_scripts)
{
  // display everything, like <!doctype HTML>, <head> tag...
  foreach($array_scripts as $script)
  {
     echo '<script src="css/'.$script.'">';
  }
  // close tags like </head>
}

您甚至可以将您的标题、描述……作为标题函数的参数。 例如,如果你的头函数有这个原型:

header($title, $array_scripts);

您将能够在 header.php 中显示标题:

// <head> ...
echo '<title>' . $title . '</title>';

【讨论】:

  • 我喜欢这个答案,但对我来说有点太复杂了 :) 不太明白。
  • 我已经编辑了答案,希望现在更清楚一点...如果您有理解困难,请告诉我 ;)
  • 感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多