我是PHP的新手。问题是,我需要在特定页面的nav中插入一个CSS类。这就是我现在的方式:
<nav class="navbar navbar-expand-md navbar-light fixed-top scrolling-navbar
<?php if (basename($_SERVER['PHP_SELF']) === 'index.php' || basename($_SERVER['PHP_SELF']) === 'shop.php' || basename($_SERVER['PHP_SELF']) === 'news.php') { echo "navbar-transparent"; } ?>
">它可以工作,但感觉很乱。我将继续研究它(也许switch语句更好?)。有没有一种更干净的方法呢?
发布于 2020-06-19 11:00:06
如果要检查某个值是否在集合中,一个简单的选择是使用in_array函数。
if(in_array(basename($_SERVER['PHP_SELF']), ['index.php', 'shop.php', 'news.php']))发布于 2020-06-19 11:58:45
如果要处理更复杂的条件类或大量动态属性,可以考虑在PHP数组中定义这些类,并动态构建整个类字符串,而不是使用各种内联条件。
例如:
<?php
$classes=["navbar", "navbar-expand-md", "navbar-light", "fixed-top", "scrolling-navbar"];
if(in_array(basename($_SERVER['PHP_SELF']), ['index.php', 'shop.php', 'news.php']))
$classes[]="navbar-transparent"; //Equivalent to array_push($classes, "navbar-transparent")
?>
<nav class="<?= implode(' ', $classes) ?>"></nav>您可以使用implode将数组转换为空格分隔的列表。如果类包含用户输入的值或其他有问题的值,那么也应该使用htmlentities来转义输出。
您甚至可以将所有属性构建为多维关联数组并将其输出。这种方法对于许多应用程序来说可能是多余的,但在更复杂的模板或组件框架中可能是实用的。
<?php
function encodeAttributes(array $attributes): string{
$encoded="";
foreach($attributes as $key=>$value){
$encoded.=' '.htmlentities($key);
if($value!==null){ //Allow for attributes without values(for instance disabled or checked)
if(is_array($value))
$value=implode(' ', $value);
$encoded.='="'.htmlentities($value).'"';
}
}
return $encoded;
}
$attributes=[
"id"=>"main_nav",
"class"=>["navbar", "navbar-expand-md", "navbar-light", "fixed-top", "scrolling-navbar"]
];
?>
<nav<?= encodeAttributes($attributes) ?>></nav>https://stackoverflow.com/questions/62462538
复制相似问题