php - 如何在php中的特定页面加载CSS

标签 php css dynamic

我想在我所有的网站页面中都有动态的 header.php,并且有很多 CSS 文件需要加载。有没有办法为每个页面加载不同的 CSS 文件?例如:

<?php if($title == "title") { ?>
<link   href="mycss.css" >
<script src="test.js"></script>
<?php } ?> 

最佳答案

您可以创建一个函数(或类)来将您的 header 和提要参数作为设置回显。这样的事情可能会起作用:

function.get_header.php

// This function will render the header
function get_header($settings = false)
    {
        ob_start();
        include("header.php");
        $data = ob_get_contents();
        ob_end_clean();
        return $data;
    }

function.get_page_css.php

// This function will act like a pseudo database return
// and will return a series of css links based on input
function get_page_css($var = false)
    {
        $css['title'][] = "/css/style1.css";
        $css['other'][] = "/css/style2.css";
        $css['title'][] = "/css/style3.css";

        if(!empty($css[$var]))
            return $css[$var];
    }

header.php

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title><?php echo (!empty($settings['title']))? $settings['title'] : "Untitled Page"; ?></title>
<head>
<?php if(!empty($settings['css']) && is_array($settings['css'])) {
    foreach($settings['css'] as $link) {
?>
<link type="text/css" rel="stylesheet" href="<?php echo $link; ?>" />
<?php  }
    }
?>
</head>

index.php

<?php
// Include the header function
include("function.get_header.php");
// Include the css return function
include("function.get_page_css.php");
// Write the header to browser using the get_page_css() function
echo get_header(array("title"=>"This Great Page!","css"=>get_page_css('title')));
?>
<body>...etc.

关于php - 如何在php中的特定页面加载CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33361274/

相关文章:

简单连接到 MySQL 时 PHP 超时 - 在 win2k8 64 位 IIS 7/FastCGI php 上 - 新安装

jquery - 仅为用户禁用滚动

html - 如何只淡化 div,而不淡化文本?

html - 如何在 CSS 中为 MVC 4 Razor 创建类层次结构?

javascript - jquery 事件绑定(bind)不适用于多个动态对象

php - Laravel Eloquent updateOrCreate 复合键

php - 在Symfony2中使用FOSElasticaBundle进行的任何搜索都为空数组

php - 如何获取具有管道的对象成员的值?

dynamic - 使用C#4对动态对象进行鸭子类型(duck typing)测试

php - 带有 png 扩展名的通用动态图像