Guns
Guns

Reputation: 2728

Include Twig Template with Vars as another twig template

I have a twig template

base.html.twig

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page Title</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

I have another twig template: content.html.twig

<div class="row">
    {{ content | raw }}
</div>

and an another one which is box.html.twig

<div class="col-md-{{ box.size|default(4) }} box-container">
    <div class="box {% if showBorder|default(true) == true %}border{% endif %} {{ box.color|default('red') }}">
        <div class="box-title">
            <h4><i class="{{ box.icon|default('fa fa-bars') }}"></i>{{ box.text }}</h4>

            <div class="tools">
                {% if showCollapseButton|default(true) == true %}
                    <a href="javascript:;" class="collapse">
                        <i class="fa fa-chevron-up"></i>
                    </a>
                {% endif %}
                {% if showCloseButton|default(false) == true %}
                    <a href="javascript:;" class="remove">
                        <i class="fa fa-times"></i>
                    </a>
                {% endif %}
            </div>
        </div>
        <div class="box-body {% if lightBody|default(false) == true %}bg{% endif %}">
            {% if showScroll|default(false) == true %}
                <div class="scroller" data-height="{{ scrollHeight|default(165) }}px">
                    {{ box.content|raw }}
                </div>
            {% else %}
                {{ box.content|raw }}
            {% endif %}
        </div>
    </div>
</div>

and the working.html.twig goes as

{% extends 'base.html.twig' %}

{% block content %}
{% endblock %}

How do i get box.html.twig into content.html.twig and the final result in working.html.twig

I know i can get content.html.twig within working.html.twig as {% include 'content.html.twig' with {'content':'Sample Content Here'} %}

but how can i get box.html.twig into the content variable to pass to include content.html.tiwg

Twig View is rendered as below:

twigLoader = new Twig_Loader_Filesystem(MVC_DIR);
        $twig = new Twig_Environment($twigLoader, array(
            'cache' => 'path/to/cache',
            'auto_reload' => true,
            'debug' => true,
        ));
        $this->twigCustomFunctions($twig);
echo $twig->render($viewPath, $this->viewVars);

Upvotes: 0

Views: 1645

Answers (1)

Javad
Javad

Reputation: 4397

I would recommend to render the box template first but set the rendered view to an array variable; then pass the variable to the content template
Something like this

$content = $twig->render('path/to/box.html.twig', array(...)); //pass the required variables for box.html instead of '...'

Now when you render the content.html you can pass the $content

echo $twig->render('path/to/content.html.twig', array(
    'content' => $content
));

Upvotes: 1

Related Questions