有没有办法在包含头文件后将样式表添加到标题中?假设我们有这段代码:
class content {
public $stylesheets = array();
public function addStylesheets($stylesheets)
{
if(!empty($stylesheets))
{
if(!is_array($stylesheets))
$stylesheets = array($stylesheets);
$this->stylesheets = array_merge($this->stylesheets, $stylesheets);
}
}
public function getStylesheets()
{
$response = '';
foreach($this->stylesheets as $stylesheet)
$response .= '<link rel="stylesheet" type="text/css" href="' . $stylesheet . '" />' . Chr(13);
return $response;
}
}
还有这个标题:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<?php
print($content->getStylesheets());
?>
</head>
<bod...
然后在文件的后面我想添加这样的样式表:
$content->addStylesheets(array('home.css', 'slider.css'));
谁能给我一个如何做到这一点的例子?
最佳答案
最终的html代码总是在最后生成。这是一个如何继续使用纯 php/html 的示例。您的 index.php 可能看起来像这样:
<?php
// ...
// Define the stylesheets to use
$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));
// ...
// Print template at the end
ob_start();
include 'your_html_template.php';
print ob_get_clean();
your_html_template.php
是问题中显示的模板文件。
您可以在执行模板之前定义变量,以便更清晰地分离 php 代码和 html。然后 index.php 看起来像这样:
<?php
// ...
// Define the stylesheets to use
$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));
$htmlStyleHeaderTags = $content->getStylesheets(); // Define variable with html header tags
// ...
// Print template at the end
ob_start();
include 'your_html_template.php';
print ob_get_clean();
然后您可以在模板中使用变量 $htmlStyleHeaderTags
:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="default.css" />
<?php print $htmlStyleHeaderTags; ?>
</head>
<bod...
关于PHP 将样式表添加到标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500848/