M
M
magary42016-12-10 15:34:53
symfony
magary4, 2016-12-10 15:34:53

How to design class rendering?

there is a certain class, let's say Product
, depending on its state, it should be rendered in different templates
{% for product in products %}
. . .
{% endfor %}
here I have a cycle that iterates 10 products, the fields of each must be analyzed and, depending on the state of the fields, select the appropriate template. those. in theory, it may turn out that 10 different heatplates will be rendered.
analysis of each instance is not only a check of field values, it may be necessary to make a request to the database if this product is in the basket, etc.
where should this logic be? what should be in the loop body?
helper?
{{ render_product(item) }}
or add this method to the class itself?
{{ item->render() }}
or else how?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2016-12-11
@magary4

Before rendering, give the Product to some "helper" service, which actually resolves 100500 entity states.
In the template itself, this should not be done - it simply displays one or another template depending on the state.

<?php
class Product {
    private $name;
}

class ProductState
{
    public function __construct(Product $product) {
        $this->product = $product;
    }

    public function getViewMetadata() {
        // Magic
    }
}

{% for productState in productStates %}
    {{ productState.name }}
    {% include productState.viewMetadata.template with productState.viewMetadata.data %}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question