【问题标题】:How to access a method and pass an argument within the template?如何在模板中访问方法并传递参数?
【发布时间】:2014-07-07 14:22:40
【问题描述】:

在我的模板中,我想检查一个实体是否与另一个实体有关系。这意味着一个对象在另一个对象的附加对象存储中。

在控制器中我可以简单地调用:

if ($product->getCategory()->offsetExists($category) {
    print 'In category ' . $category->getName();
}

但我无法在模板中找出正确的语法。我尝试了那些没有运气的人(每次都评估为true):

<f:if condition="{product.category.offsetExists(category)}">true</f:if>    
<f:if condition="{product.category.offsetExists({category})}">true</f:if>

这甚至可以在模板中实现吗?

【问题讨论】:

    标签: typo3 fluid extbase typo3-6.1.x typo3-6.2.x


    【解决方案1】:

    您只能从 Fluid 通过 Getter 访问属性,不带参数,但您可以实现自己的 ViewHelper 来检查。作为参数,您可以使用您的产品和类别。然后您可以通过 Fluid 以这种方式调用 ViewHelper:

    <vh:checkOffset product="{product}" category="{category}" />
    

    或内联

    {vh:checkOffset(product: product, category: category)}
    

    在 ViewHelper 中,您可以像在 Controller 中那样检查它:

    public function render($product, $category){
        return ($product->getCategory()->offsetExists($category));
    }
    

    【讨论】:

    • 再次非常感谢 - 我完全忘了回到这里并竖起大拇指。
    【解决方案2】:

    除了 sretuer 的 回答之外,我只会提到您可以创建 VH,它将有条件地显示块,例如:

    文件typo3conf/ext/your_ext/ViewHelpers/CheckOffsetViewHelper.php

    <?php
    namespace VENDORNAME\YourExt\ViewHelpers;
    
    class CheckOffsetViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
        public function render() {
            return ($product->getCategory()->offsetExists($category)) 
                   ? $this->renderChildren()
                   : '';
        }
    }
    ?>
    

    所以你可以在视图中使用它:

    {namespace vh=VENDORNAME\YourExt\ViewHelpers}
    
    <vh:checkOffset product="{product}" category="{category}" >
        Display this only if product is in category 
    </vh:checkOffset>
    

    当然你需要根据你的扩展修复VENDORNAMEYourExt,可以在每个控制器、模型、存储库等的开头找到。

    【讨论】:

    • 再次非常感谢 - 我完全忘了回到这里并竖起大拇指。
    • 我不敢碰你的代码。 @thomas-hörner 确实为您添加了 NAA 评论:您忘记了方法 renderChildren 的括号。如果我的代码中没有括号,它就无法运行。返回 ($product->getCategory()->offsetExists($category)) ? $this->renderChildren(): "";
    • @bummi 和 Thomas 感谢您指出缺少的括号,这是 StackOverflow 随时可以编辑其他人的答案/问题,特别是如果它们包含令人讨厌的错误;顺便说一句,对不起;)我从头顶写了
    • 根据book类文件必须在typo3conf/ext/your_ext/Classes/ViewHelpers/CheckOffsetViewHelper.php下,否则自动加载器将无法通过命名空间找到类
    【解决方案3】:

    您可以考虑https://fluidtypo3.org/viewhelpers/vhs/master/Condition/Iterator/ContainsViewHelper.html,它设计用于在 Fluid 中创建条件,检查数组或迭代器是否包含另一个对象,并且在 thenelse 参数以及 f:then 和 @987654326 方面的工作方式与 f:if 完全相同@子节点。

    【讨论】:

      猜你喜欢
      • 2016-04-26
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多