有没有办法缩短这个if语句?
<?php
$features = get_field('features_&_amenities');
if($features){ ?>
<a href="#<?php the_field('features_&_amenities'); ?>">Features & Amenities</a>
<?php } else { ?>
<a class="none" href="#<?php the_field('features_&_amenities'); ?>">Features & Amenities</a>
<?php } ?>
我用这个来显示数据库中的advance custom field数据,我想知道有什么方法可以让它缩短,如果有的话......
感谢所有的建议。和解释。
答案 0 :(得分:2)
<a class="
<?php echo $features ? '' : 'none'; ?>"
href="#
<?php the_field('features_&_amenities'); ?>">
Features & Amenities</a>
答案 1 :(得分:2)
两者之间的唯一区别是class="none"
。只需有条件地添加:
<?php
$features = get_field('features_&_amenities');
$class = !$features ? ' class="none"' : '';
?>
<a <?=$class?>href="#<?php the_field('features_&_amenities'); ?>">Features & Amenities</a>
当然还有很多其他的方法,这只是一个。
答案 2 :(得分:1)
因为它是一个php文件,所以将php代码与html代码分开会更好。
$the_field = the_field('features_&_amenities');
$features = get_field('features_&_amenities');
$html_class = $features ? 'class="none"' : '';
echo "<a $html_class href=\"#$this_field\">Features & Amenities</a>";