0
\$\begingroup\$

Basically, I'm lazy.

And so, since I don't want to write multiple times the same table HTML, I've made a very ... convoluted macro.

{% macro table(rows, options = {}) %}
    {% set default = {
        'width': '100%'
    } %}
    {% set options = default|merge(options) %}

    <table
        {% for attr, value in options %}
            {{ attr }}="{{ value }}"
        {% endfor%}
    >
        {% for row in rows if row and row is iterable %}
            <tr>
                {% for cell in row %}
                    {% if cell is iterable %}
                        {% if cell.content is iterable %}
                            {% for content in cell.content %}
                                <td
                                    {% for attr, value in cell if attr != 'content' %}
                                        {{ attr }}="{{ value }}"
                                    {% endfor%}
                                >{{ content|raw }}</td>
                            {% endfor %}
                        {% else %}
                            <td
                                {% for attr, value in cell if attr != 'content' %}
                                    {{ attr }}="{{ value }}"
                                {% endfor%}
                            >{{ cell.content|raw }}</td>
                        {% endif %}
                    {% else %}
                        <td>{{ cell|raw }}</td>
                    {% endif %}
                {% endfor %}
            </tr>
        {% endfor %}
    </table>
{% endmacro %}

The idea is to pass it an array with all the rows, and then all the cells.
And each cells' elements will be displayed as raw HTML (intentional).

However, you can pass an hash with the key content and all the attributes you want to set for a particular cell.
Each attribute will be added directly to the <td>.

It is also possible to pass an array as the content, to then apply all the attributes to the <td>s.


As you can see, there's a lot of whitespace. What can I do to make it more readable?

What else can I do to make it easier to use?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.