为特定页面包含样式表的最佳方法是什么? [英] What is the best way to include a style sheet for a specific page?
问题描述
感谢您的观看.
我的网站使用PHP在每个页面上都包含相同的页眉和页脚.
My website includes the same header and footer for each page using PHP.
我想要只专门用于特定页面的样式表,因此请使用适当的标记来放置样式.
I wanted a style sheet that only applied specifically for a certain page, so put the style in using the appropriate tag.
...<body><style type="text/css"> /* what ever */ </style></body>...
在我测试过的所有浏览器中,样式表均已正确处理,但是W3C并未正确验证样式表,因为它位于body标签内部而不是head内.
The style sheet is processed correctly in all browsers I tested, however it is not validated correctly by W3C because it's located inside the body tag instead of the head.
我的问题是:
如果我不能将样式表放在body标签中,最好的添加方式是什么?我可以在PHP标头中引用样式表,但我不希望再有一个HTTP请求来获取如此小的文件.你会怎么做?什么是最草率的方式呢?尽管不应将样式标签放在< body>中,但浏览器仍可以对其进行正确处理.
My question is:
If I can't put the style sheet in the body tag, what is the best way to include it? I can reference the style sheet in the PHP header, but I'd rather not have another HTTP Request for such a small file. How would you do it? What is the least sloppy way to do it? Although the style tag shouldn't be in <body>, it is still processed correctly by browsers.
推荐答案
最好的方法是使用MVC框架来缓冲视图文件,并允许在输出之前将标签动态添加到头部.
The best way would be to use a MVC framework that buffers your view file, and allow tag to be dynamically added to the head before output.
这是一种非常简单的方法:
Here is a ultra simple way of doing it:
index.php:
index.php:
<?php
class Page {
private static $head = array();
private static $content = '';
static function add_head($tag) {
self::$head[] = $tag;
}
static function render_head() {
foreach (self::$head as $tag) echo $tag;
}
static function render_content() {
echo self::$content;
}
static function read_content($file) {
ob_start();
require $file;
self::$content = ob_get_clean();
}
static function render_layout($file) {
require $file;
}
}
Page::read_content('view.php');
Page::render_layout('layout.php');
?>
layout.php:
layout.php:
<html>
<head><?php Page::render_head(); ?></head>
<body>
<div id="header"></div>
<div id="content"><?php Page::render_content(); ?></div>
<div id="footer"></div>
</body>
</html>
view.php:
<?php Page::add_head('<title>Hello World!</title>'); ?>
<h1>Hello</h1>
<p>World</p>
这篇关于为特定页面包含样式表的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!