我正在尝试根据php中的特定页面创建一个正文类名。我需要做的是首先定义一个变量然后检查变量是否存在,然后如果它存在则显示那个变量,否则如果它是其他东西,那么做其他事情,或者如果什么也没有显示任何变量。
<body<?php if (defined('PAGE_KEY') && var == "homepage") echo " class=\"homepage\"";
elseif (defined('PAGE_KEY') && var == "page3") echo " class=\"page3\"";
elseif (defined('PAGE_KEY') && var == "page12") echo " class=\"page12\""; ?>>
此代码位于我的head.php
。
我的想法是首先检查变量是否已定义,如果是,则检查变量的定义,然后根据该变量显示相应的类。
目标是例如在page12上,body标签看起来像这样:
<body class="page12">
但是例如第55页的body标签(我不想显示一个类)看起来像这样:
<body>
通过这样做,我现在能够专门为标题中正好位于标题内的页面定义css。
问题首先我不知道如何在页面中定义变量,其次我不知道如何正确编写上面的PHP代码。
尝试,例如在第12页,我会有这个代码:
<?php PAGE_KEY = "page12" ?>
此代码例如位于page12.php
。
还要记住,变量将在body标签之后出现。
我还想过尝试查看页面网址是什么,但我认为这只会让事情变得太复杂。
<小时/> <小时/> <小时/>
根据@Jordi的建议,如何:
<body class="<?php echo PAGE_KEY ?>">
on head.php
。
然后在page12.php
,这个:
<?php PAGE_KEY = "page12" ?>
,例如在page5.php
上:
<?php PAGE_KEY = "page5" ?>
以便在这些相应的页面上,body标签显示:
on page5.php
:
<body class="page5">
并在page12.php
上,正文标记会显示:
<body class="page12">
这是对的吗?
@Jose提出这个建议,这是对的吗?例如,在page12.php
上,要将变量定义为&#39; page12&#39;,请执行以下操作:
<?php define("PAGE_KEY", "page12"); ?>
这是你建议做的吗?
<小时/> <小时/> <小时/>
确定!这个问题解决了。我只需要在head.php
包含之前的单个页面中添加代码,以便我可以定义它。谢谢你的帮助! :)
答案 0 :(得分:1)
您可以使用和定义这样的常量:
<?php
define( "PAGE_KEY","homepage" );
?>
.
.
.
<body<?php echo " class=\"" . constant( "PAGE_KEY" ) . "\""; ?>>
另一页:
<?php
define( "PAGE_KEY","page5" );
?>
.
.
.
<body<?php echo " class=\"" . constant( "PAGE_KEY" ) . "\""; ?>>
您只需更改常量,其余部分对每个页面都相同。
编辑#1:
<body
<?php
define( "PAGE_KEY","homepage" );
echo " class=\"" . constant( "PAGE_KEY" ) . "\"";
?>
>
编辑#2:
<?php
define( "PAGE_KEY","homepage" );
?>
.
.
.
<?php
include( "head.php" >
?>
现在, head.php 是这样的:
echo "<body class=\"" . constant( "PAGE_KEY" ) . "\">";
答案 1 :(得分:0)
从这样的事情开始。
<?php
//each page and its class. Many pages can share the same class. If a page doesn't
//have a class, don't include it.
$classes = [
'homepage'=>'home_class',
'page1'=>'base_class',
'page2'=>'home_class',
'page3'=>'special_class'
];
//Adjust this from one page to the next
$this_page = 'homepage';
//get the class corresponding to current page, or '' if no class
$this_class = isset($classes[$this_page])? $classes[$this_page] : '';
?>
//insert the class for this page.
<body class="<?=$this_class ?>">
您可以通过将$classes
数组移动到另一个文件(例如配置文件)并将其包含在所有页面中来改进它。这样你就不必在每个页面上重写数组(一个坏主意,因为很难做出改变,很容易出错)