我正在寻找添加if / else语句,根据需要显示不同的HTML。我的问题是如何改进这段代码?是否有更精确的方式来呈现此代码?
<?php if ('Images' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Images</h1>
<div class="images">...</div>
<? } elseif ('Slideshow' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Slideshow</h1>
<div class="slideshow">...</div>
<? } elseif ('Video' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Video</h1>
<div class="video">...</div>
<? } elseif ('Audio' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Audio</h1>
<div class="audio">...</div>
<?php } ?>
答案 0 :(得分:1)
<?php
// Only call the function once (performance)
$post_id = get_post_meta($post->ID, "project_type", true);
// Use a whitelist to validate
$whitelist = array("Images", "Slideshow", "Video", "Audio");
// Check if given post ID is valid
if (in_array($post_id, $whitelist) === true) { ?>
<h1><?= $post_id ?></h1>
<div class="<?= strtolower($post_id) ?>">...</div>
<?php } ?>
是的,此方法未考虑<div>
元素中可能发生的情况。因为这不是你问题的一部分。如果有很多事情发生,我会提出一种面向对象的方法。另一个坏方法是switch语句。
<?php
switch (get_post_meta($post->ID, "project_type", true)) {
case "Images": ?>
<h1>Images</h1>
<div class="images">...</div>
<?php break;
case "Slideshow": ?>
<!-- Same story again ... -->
<?php break;
} // End switch
使用OOP,我们可以创建如下内容:
<?php
namespace Stackoverflow;
abstract class MyBaseTemplate {
protected $title;
protected $class;
protected $content;
public function __toString() {
return "<h1>{$this->title}</h1><div class='{$this->class}'>{$this->content}</div>";
}
}
class Images extends MyBaseTemplate {
public function __construct() {
$this->title = "Images";
$this->class = "images";
$this->content = "...";
}
}
class Slideshow extends MyBaseTemplate {
// Init
}
// In the other file instead of if/else and switch
$post_id = get_post_meta($post->ID, "project_type", true);
$class = "\\Stackoverflow\\{$post_id}";
if (class_exists($class) === true) {
echo new $class();
}
答案 1 :(得分:0)
有时将所有标记放在echo语句中会更清晰,但只有它是简单的标记,并且结果实际上比在上面的php语句中混合更具可读性。例如:
<?php
if (...) {
echo "<h1>Images</h1>"
echo "<div class=\"images\">...</div>"
} else if(...) {
echo "<h1>...</h1>"
}
?>
答案 2 :(得分:0)
Fleshgrinder是对的,你可以通过一次只使用get_post_meta来改善它。
如果每个html的内容不同,我可能会使用开关而不是else / elseif / etc ......
$project_type = get_post_meta($post->ID, 'project_type', true);
switch ( $project_type ) {
case 'Images':
echo '<h1>Images</h1>';
echo '<div class="images">...</div>';
break;
case 'Slideshow':
echo '<h1>Slideshow</h1>';
echo '<div class="slideshow">...</div>';
break;
case 'Video':
echo '<h1>Video</h1>';
echo '<div class="video">...</div>';
break;
case 'Audio':
echo '<h1>Audio</h1>';
echo '<div class="audio">...</div>';
break;
}