简体   繁体   English

根据身体类别包括

[英]Include depending on body class

I'm trying to figure out how to check for a single class on the body tag then include a file. 我试图弄清楚如何在body标签上检查单个类,然后包括一个文件。

My header.php contains: 我的header.php包含:

</head>
<?php $class = BODY_CLASS; ?>
<body class="<?php echo $class; ?>" id="top">

And in the body: 在体内:

<?php if (isset($class) && $class == 'work') { ?>
    <?php include( $_SERVER['DOCUMENT_ROOT'] . MODULES . "_social.php"); ?>
<?php }; ?>

This works fine so long as I only have a single class on the body tag, but what if I have multiple tags? 只要在body标签上只有一个类,这就可以正常工作,但是如果我有多个标签怎么办?

for instance my body tag outputs this: 例如我的身体标签输出以下内容:

<body id="top" class="work project1">

How can I check for the work even if other classes exist? 即使存在其他类,如何检查work

只需稍微更改一下if语句,然后将$class explode()一个空格,然后使用in_array()在数组中搜索值即可,例如

if (in_array("work", explode(" ", $class))) {

You can use different approaches, for example, if you are sure that body class is always the first word, you can try this 您可以使用不同的方法,例如,如果您确定body类别始终是第一个单词,则可以尝试以下方法

$class=current(explode(" ",BODY_CLASS)); //class that you should check
if($class=='')

or 要么

switch($class) { }

which splits the BODY_CLASS string and gets the first value. 它拆分BODY_CLASS字符串并获取第一个值。

Anyway, you can also try searching into an array, like this 无论如何,您也可以尝试像这样搜索数组

if(in_array('classname',explode(" ",BODY_CLASS)))

You could use explode together with in_array : 您可以将explodein_array一起使用:

if (isset($class) && in_array('work', explode(' ', $class))) { ...

References: http://php.net/manual/en/function.explode.php http://php.net/manual/en/function.in-array.php 参考: http : //php.net/manual/en/function.explode.php http://php.net/manual/en/function.in-array.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM