PHPTAL:优雅地处理未定义的变量

发布于 2024-07-13 06:06:41 字数 96 浏览 5 评论 0原文

如果我使用尚未放入作用域的变量,PHPTAL 会引发异常。 有没有办法让 PHPTAL 恢复到正常的默认值,例如在布尔上下文中评估为 false,在字符串上下文中评估为空白等?

If I use a variable that hasn't been put into the scope, PHPTAL throws an exception. Is there any way of making PHPTAL fall back to graceful defaults, for example evaluating to false in a boolean context, to a blank in a string context, etc?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜空下最亮的亮点 2024-07-20 06:06:41

您可以将“| Nothing”添加到 TALES 表达式中,或在 php: 表达式中使用 isset()

<p tal:attributes="class php:isset(class)?class:NULL" 
   tal:content="variable | nothing" />

如果你有大量的代码依赖于某个变量,那么使用 exists: 修饰符:

<div tal:condition="exists:variable">
…
</div>

如果你想伪造任何变量的存在,这是可以做到的,但我不推荐它(它会隐藏拼写错误):

class FakeAll extends stdClass
{
    function __get($var){return "";}
    function __isset($var){return true;}
}

$p = new PHPTAL();
$p->getContext()->setGlobal(new FakeAll());

You can add "| nothing" to TALES expressions or use isset() in php: expressions.

<p tal:attributes="class php:isset(class)?class:NULL" 
   tal:content="variable | nothing" />

If you have larger bit of code that relies on a certain variable, then use exists: modifier:

<div tal:condition="exists:variable">
…
</div>

If you want to fake existence of any variable, it can be done, but I don't recommend it (it will hide typos):

class FakeAll extends stdClass
{
    function __get($var){return "";}
    function __isset($var){return true;}
}

$p = new PHPTAL();
$p->getContext()->setGlobal(new FakeAll());
德意的啸 2024-07-20 06:06:41

还有较短的版本:

<input type="text" name="id" value="${data/formvalues/id|nothing}" />

also shorter version:

<input type="text" name="id" value="${data/formvalues/id|nothing}" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文