PHP 将样式表添加到标题

标签 php html class stylesheet magic-methods

有没有办法在包含头文件后将样式表添加到标题中?假设我们有这段代码:

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/

相关文章:

c++ - std::成员函数的异步调用

php - WordPress 500(URL 重写模块错误。)

javascript - 定期调用AJAX是否会给服务器和浏览器本身带来负担?

android - 使用 Simperium 从 Android 更新 HTML 列表

javascript - 将 td 值传递给 JavaScript

javascript - 图像输入不会显示在 $_FILES 中

php - WooCommerce 在前端自定义日期后显示产品总销售额

c++ - 我在这里正确使用删除吗?

java - 增强for循环中的类方法