【问题标题】:PHP Adding stylesheets to headerPHP将样式表添加到标题
【发布时间】:2015-04-14 13:38:53
【问题描述】:

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

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 分开,你可以使用 smarty 或 twig 之类的模板引擎。但是如果你不想使用它,那么最后生成你的 html,首先执行你的 php 代码,然后渲染 html。所以首先 if (something) { $content-&gt;addStyleSheet($style)} ... (some other code) ... echo $myTemplate; 其中 $myTemplate 包含您的网站

标签: php html class stylesheet magic-methods


【解决方案1】:

@szapio 已经很伤心了,在最后构建 HTML 更有意义。

无论如何,一个“肮脏”的解决方案是通过将 在&lt;/body&gt;-tag 之前(在&lt;head&gt; 中包含jQuery):

<script>
$(document).ready(function() {
    $('head').append('<link rel="stylesheet" href="test.css" />');
});
</script>

您真的不应该考虑这样做,因为 CSS 文件将在其他所有内容之后加载,这意味着只要 CSS 文件尚未加载,您就会看到未设置样式的元素……

【讨论】:

    【解决方案2】:

    最终的 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...
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2021-12-14
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多