-->

How to access a method and pass an argument within

2019-08-26 04:54发布

问题:

In my template I want check whether an entity has a relation to another one. Meaning one object is in an attached Object Storage of another one.

In the controller I can simply call:

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

But I can't figure out the correct syntax in the template. I tried those without luck (both evaluate to true everytime):

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

Is this even possible within the template?

回答1:

Additionally to sretuer's answer, I'll only mention that you can create VH which will display block conditionally like:

File 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()
               : '';
    }
}
?>

So you can use it in the view:

{namespace vh=VENDORNAME\YourExt\ViewHelpers}

<vh:checkOffset product="{product}" category="{category}" >
    Display this only if product is in category 
</vh:checkOffset>

Of course you need to fix VENDORNAME and YourExt according to your extension, can be found at the beginning of every controller, model, repository etc.



回答2:

You can only access properties via Getter from Fluid with no parameters, but you can implement an own ViewHelper to check that. As parameters you can use your Product and the Category. Then you can call your ViewHelper from Fluid this way:

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

or inline

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

Within your ViewHelper you can check this in the way you've done it in your Controller:

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


回答3:

You may consider https://fluidtypo3.org/viewhelpers/vhs/master/Condition/Iterator/ContainsViewHelper.html which is designed for creating conditions in Fluid that check if an array or Iterator contains another object and works exactly like f:if regarding then and else arguments and f:then and f:else child nodes.