在IF语句的第一部分中插入HTML

问题描述 投票:-1回答:3

引用an answer to a previous question,您可以使用以下语法在IF语句中中断PHP:

<?php if (get_field ('member_only_content')): ?>
    <span>Put HTML here</span>
<?php else: ?>
    <span>Put HTML here</span>
<?php endif;?> 

如果我只想在本声明的第一部分中打破php并使用HTML,该怎么办?

<?php if (get_field ('member_only_content')): ?>
    <span>Put HTML here</span>
<?php else: ?>
<?php //more php code here ?>
<?php endif;?>

这是实现它的唯一方法(多个php标签),还是有另一种(可能是更整洁的)方式?

php html if-statement syntax
3个回答
0
投票

你可以简单地关闭PHP块:

<?php
if (get_field ('member_only_content')):
    echo '<span>Put HTML here</span>';
else:
    foo();
    bar();
    // ... your PHP code
endif;´
?>

如果只有1-2行简单的HTML,使用echo输出HTML效果很好。

如果您要输出更复杂的HTML结构或更多行,那么我建议关闭PHP块,编写HTML然后再次打开PHP块:

<?php
if (get_field ('member_only_content')):
?>

    <span>Here be some complex HTML</span>
    ...

<?php
else:
    foo();
    bar();
    // ... your PHP code
endif;´
?>

1
投票
<?php 
if (get_field ('member_only_content'))
    echo '<span>Put HTML here</span>';
?>

如果if块中只有一个语句,则可以跳过else部分。


0
投票

您不需要为每一行添加PHP标记。

还有另一种方式:

<?php
First line code
Second line code
...
?>

只需要一个标签

© www.soinside.com 2019 - 2024. All rights reserved.