我想知道在尝试构建由html和php组成的动态html页面时,是否有标准规则或方法。
例如,大多数时候,我会对脑海中弹出的内容进行编码,我的php最终会变成这样:
<div class="front-title-blocks">
<div class="table">
<div class="table-row">
<?php while ($wp_query->have_posts()) : $wp_query->the_post();
if( have_rows('table_row') ):
while ( have_rows('table_row') ) : the_row(); ?>
<div class="table-cell">
<?php the_sub_field('single_cell'); ?>
</div>
<?php endwhile; else :
// no row found
endif; ?>
<?php endwhile; ?>
</div>
</div>
</div>
然后我注意到,执行完全相同功能的相同代码可以像这样重写。
<?php
while ($wp_query->have_posts()) : $wp_query->the_post();
function repeaterField(){
$output='';
if( have_rows('table-b-table') ):
while ( have_rows('table_row') ) : the_row();
$output .= "<div class='table-cell'>".get_sub_field('single_cell')."</div>";
endwhile; else : // no row found
endif;
return $output;
}
$output = "<div class='front-title-blocks'>
<div class='table'>
<div class='table-row'>".repeaterField()."</div>
</div>
</div>";
endwhile;
echo $output;
?>
我注意到的区别:
•第一个例子有多个打开和关闭php标签,它们在html和php之间连续切换。
•第二个例子倾向于一直使用php,并且可以使用变量轻松地进行回显。
•第二个例子需要更长的时间来构建和重新排列。
•为了便于安排,我觉得第二个例子更有条理,但我确实注意到第一个例子更容易阅读。
如有任何建议,不胜感激。
第一个选项是"更好"(或者我更喜欢这个),原因有很多:因为它更可读,有了代码编辑器,你可以获得语法帮助和自动完成,页面加载更快。
另一件需要考虑的事情是,您将在第二种方法中处理可能导致错误的双引号和简单引号:
echo "<div id='a'"+$var+"'...>";
但这两个选项是有效的。
还有其他类似的问题:用echo输出HTML在PHP中被认为是一种糟糕的做法?
第一种方法很好。第二个是坏主意。
<?php ?>
内部的所有代码都被发送到PHP进行解释。这意味着您的网站速度较慢。所以不要毫无理由地回显HTML标记。
您可以尝试一些模板引擎,如Twig,用于服务器端页面生成。
例如,Twig允许你这样做:
{{ var }}
而不是这个:
<?php echo $var ?>
你也可以这样做:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
Twig参考
gogle:php模板引擎-用于其他模板引擎
还有第三种选择:
<html>
....
<body>
....
<?php
while ($wp_query->have_posts()) : $wp_query->the_post();
if (have_rows('table-b-table')):
while (have_rows('table_row')) : the_row();
$var1 = get_sub_field('single_cell');
include 'template.php';
endwhile;
endif;
endwhile
?>
...
</body></html>
template.php
<div class='front-title-blocks'>
<div class='table'>
<div class='table-row'>
<div class='table-cell'>
<?= $var1 ?>
</div>
</div>
</div>
</div>
就我个人而言,我更喜欢这个,因为它最大限度地减少了PHP标记中的HTML代码。
是的,第一个选项很好,用
但我们有一些短代码标签,比如您应该在php.ini文件中为缩写