html 中的 php 变量别无他法: <?php echo $var;?> [英] php variable in html no other way than: <?php echo $var; ?>
问题描述
我在混合 HTML 和 PHP 中做了很多工作,大多数时候我只想要包含一些 PHP 变量的纯 HTML,所以我的代码如下所示:
I work a lot in mixed HTML and PHP and most time I just want solid HTML with a few PHP variables in it so my code look like this:
<tr><td> <input type="hidden" name="type" value="<?php echo $var; ?>" ></td></tr>
这很丑陋.是不是有更短的,更像下面这样的?
Which is quite ugly. Isn't there something shorter, more like the following?
<tr><td> <input type="hidden" name="type" value="$$var" ></td></tr>
这是可能的,但你会被 ""
卡住(你必须用 ''
替换它们)并且布局消失了
This is possible to but you get stuck with the ""
(you have to replace them all with ''
) and the layout is gone
echo "<tr><td> <input type="hidden" name="type" value="$var" ></td></tr>"
还有什么更好的吗?
推荐答案
您的代码有短标签版本,现在完全可以接受使用,尽管有过时的建议:
There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:
<input type="hidden" name="type" value="<?= $var ?>" >
其中(PHP 5.4 之前)需要在您的 php 配置中启用短标签.它的功能与您键入的代码完全相同;这些行在其内部实现中实际上完全相同:
which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:
<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>
关于内置解决方案.有很多 3rd 方模板库可以更轻松地将数据嵌入到您的输出中,smarty 是个好地方开始.
That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.
这篇关于html 中的 php 变量别无他法: <?php echo $var;?>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!