I
I
Ilya2020-04-05 16:20:45
PHP
Ilya, 2020-04-05 16:20:45

How to add a variable to a specific twig 1.* template?

Twig 1.* is used as a standalone library (not part of symfony or something like that).

There is a certain template that is connected in other templates. This include template requires several variables. How can I specify them once instead of passing them from the controller each time? Perhaps it will be clearer with examples.

For those who are familiar with Laravel:
I need an analogue of \View::composer();

Let's say we are making an online store, several pages, most of them have a header and a footer.
In the header, we need to display a list of categories.

Rendering in the controller looks something like this:

spoiler

protected function render(string $view, array $params = [])
{
  $loader = new FilesystemLoader(base_path('/resources'));

  $twig = new Environment($loader, ['cache' => base_path('/var/cache/twig'), 'debug' => true]);

  $content = $twig->render($view, $params);

  return Response::create($content);
}


There is a template 'template.twig'
spoiler

<!DOCTYPE html>
<html lang="ru">
  <head>
  <title>Интернет-магазин</title>
  </head>
  <body>
    <header>
      <ul>
        {% for category in categories %}
          <li><a href="{{ category.url}}">{{ category.name}}</a></li>
        {% endfor %}
      </ul>
    </header>
    <div class="content">
      {% block content %}{% endblock %}
    </div>
    <footer></footer>
  </body>
</html>


And there are several templates that extend it.
spoiler

{% extends "template.twig" %}

{% block content %}
  Тут какой-то контент, у каждой страницы свой
{% endblock %}



Make sure the categories variable is always available in template.twig

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Antonio Solo, 2020-04-05
@New_Horizons

I create a global variable of type "website" in twig 1, and already inside the templates I pull its methods as needed
addGlobal

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question