为什么我的简单 "if" 不起作用? PHP

Why does my simple "if" not work? PHP

所以,我正在尝试做一些非常简单的事情:检查一个数字是否等于另一个数字 - 但出于某种原因它就是不想工作。

$exhibitions = "20,21,24";
$parent = "[[*parent]]";
$id = "[[*id]]";

if ($id == 5) {
    $chunk = "listExhibitions";
}
if (stripos($exhibitions, $parent) == TRUE) {
    $chunk = "Exhibitions";
}
return "[[$" . $chunk . "]]";

这是我尝试开始工作的第一个 "if"。如果我放一个!在 == 之前,页面显示 "listExhibitions" 块 - 但当 id 等于 5 时,我需要这样做。我也试过在数字周围加上 ' '。另外,当我简单地输出 $id 时,数字 5 出现了。

我做错了什么?

您引用 ID 的方式只能在视图中使用。这似乎是一个控制器。试试这样:

$exhibitions = "20,21,24";
$parent = $modx->resource->get('parent');
$id = $modx->resource->get('id');

if ($id == 5) {
    $chunk = "listExhibitions";
}
if (stripos($exhibitions, $parent) == TRUE) {
    $chunk = "Exhibitions";
}
return "[[$" . $chunk . "]]";

您期望在这里发生的是 Modx 自动处理您的 ID 和 PARENT 占位符并将它们传递到您的代码段中。 Modx 不会为你做这些,你要么必须在 $scriptProperties 数组中明确地传递它们~要么~正如 Marvin 指出的那样从 modResource 对象中获取这些属性(modx 将假定为当前资源)

要显式传递它们,请将占位符添加到代码段调用中:

[[~MyCustomSnippet? &id=`[[*id]]` &parent=`[[*parent]]`]]

在那种情况下,Modx 将在解析您的页面、模板或块时填充占位符(无论您碰巧调用了该代码段。

如果您正在处理 CURRENT 资源的 ID 和 PARENT; Marvin 的示例可以工作,但我相信您必须先获取当前资源对象。

$resource = $modx->getObject('modResource');

您必须查看有关该文档的文档。 (或测试)

更新

我们三个人在聊天中解决了这个问题并提出了以下解决方案:

通过这种方式调用代码段:

[[!MyCustomSnippet? &id=`[[*id]]`]]

片段内容:

<?php

$id = isset($scriptProperties['id']) ? $scriptProperties['id'] : FALSE; // get id passed with snippet

$exhibitions = array(20,21,24);

if(!$id){
    $id = $modx->resource->get('id'); // get the current resource id if it was not passed
}

$resource = $modx->getObject('modResource', $id); // get the resource object

$parent = $modx->resource->get('parent'); // get the parent id from the resource object

$output = '';

if ($id == 5) {
    $chunk = "listExhibitions";
}

if (in_array($parent, $exhibitions)) {
    $chunk = "Exhibitions";
}

$output = $modx->getChunk($chunk);

return $output;

这将使用代码段调用中传递的 ID,或者如果未传递 ID 则假定当前资源并根据该 ID 从资源对象中获取父 ID。