Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a twig file and pass variables from a separate file?

Tags:

gulp

twig

I have container.twig including component.twig and passing an object called 'mock'.

In container.twig:

{% set mock = {
    title : "This is my title"
}
%}

{% include 'component.twig' with mock %}

This is working fine but I want to move the mock data to its own file. This isnt working:

Container.twig

{% include 'component.twig' with 'mock.twig' %}

In mock.twig

{% set mock = {
    title : "This is my title"
}
%}

Im using gulp-twig but it works like standard twig in most respects. https://github.com/zimmen/gulp-twig

like image 495
Evanss Avatar asked Apr 28 '16 16:04

Evanss


People also ask

How do I transfer data from Twig to JavaScript?

Using a data attribute to pass a single field If you have a small amount of data to share with JavaScript then use a named data attribute. First add the named data attribute to an element. ❗ If the value has a chance of containing a " or < then add an escape filter: ...

How do you dump variables in Twig?

Using the Manage administrative menu, navigate to Configuration > Development > Devel settings (admin/config/development/devel) and under the heading, Variables Dumper, select Kint, then Save configuration. Like the dump function, kint() will not display any output unless debugging is enabled.

How do I add a global variable in Twig?

If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.

Can you use Twig in JavaScript?

Now that your JS code lives alongside Twig, you can easily transfer Twig variables into Javascript. For example: alert({{twig_variable|json_encode}}); From Twig point of view, JS code is just text string - that's why we can just concate Twig variables with text that make up JS code.


2 Answers

The problem

Twig context is never stored in the template object, so this will be very difficult to find a clean way to achieve this. For example, the following Twig code:

{% set test = 'Hello, world' %}

Will compile to:

<?php

class __TwigTemplate_20df0122e7c88760565e671dea7b7d68c33516f833acc39288f926e234b08380 extends Twig_Template
{
    /* ... */

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $context["test"] = "Hello, world";
    }

    /* ... */
}

As you can see, the inherited context is not passed to the doDisplay method by reference, and is never stored in the object itself (like $this->context = $context). This deisgn allow templates to be reusable, and is memory-friendly.

Solution 1 : using global variables

I don't know if you are aware of Global Variables in Twig. You can do a bunch of hacks with them.

The easiest usage is to load all your globals inside your twig environment.

$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);
$env->addGlobal('foo', 'bar');
$env->addGlobal('Hello', 'world!');

Then, you can use {{ foo }} and {{ Hello }} in your whole application.

But there are 2 problems here:

  • As you're trying to load variables from twig files, I assume you have lots of variables to initialize depending on your feature and don't want to load everything all time.

  • you are loading variables from PHP scripts and not from Twig, and your question want to import variables from a twig file.

Solution 2 : using a Twig extension

You can also create a storage extension that provide a save function to persist some template's context somewhere, and a restore function to merge this stored context in another one.

proof_of_concept.php

<?php

require __DIR__.'/vendor/autoload.php';

class StorageTwigExtension extends Twig_Extension
{
    protected $storage = [];

    public function getFunctions() {
        return [
            new Twig_SimpleFunction('save', [$this, 'save'], ['needs_context' => true]),
            new Twig_SimpleFunction('restore', [$this, 'restore'], ['needs_context' => true]),
        ];
    }

    public function save($context, $name) {
        $this->storage = array_merge($this->storage, $context);
    }

    public function restore(&$context, $name) {
        $context = array_merge($context, $this->storage);
    }

    public function getName() {
        return 'storage';
    }
}

/* usage example */

$loader = new Twig_Loader_Filesystem(__DIR__.'/view');
$env = new Twig_Environment($loader);

$env->addExtension(new StorageTwigExtension());

echo $env->render('test.twig'), PHP_EOL;

twig/variables.twig

{% set foo = 'bar' %}
{% set Hello = 'world!' %}
{{ save('test') }}

twig/test.twig

{% include 'variables.twig' %}
{{ restore('test') }}
{{ foo }}

Note: if you only want to import variables without actually rendering what's inside twig/variables.twig, you can also use:

{% set tmp = include('variables.twig') %}
{{ restore('test') }}
{{ foo }}

Final note

I'm not used to the JavaScript twig port, but it looks like you can still extend it, that's your go :)

like image 84
Alain Tiemblo Avatar answered Oct 14 '22 16:10

Alain Tiemblo


Because of Twig's scoping rules (which I assume are replicated by the gulp version), you cannot pass variables up from a child template without creating a helper function. The closest thing you can do is to use inheritance to replicate this.

As such, your mock.twig file would become

{% set mock = {
      title : "This is my title"
  }
%}
{% block content %}{% endblock %}

Your container.twig would then become

{% extends 'mock.twig' %}
{% block content %}
    {% include 'component.twig' with mock %}
{% endblock %}

This achieves your goals of separating the mock content from the templates for the most part and, using dynamic extends, you can do something like

{% extends usemock == 'true'
    ? 'contentdumper.twig'
    : 'mock.twig' %}

with a contentdumper.twig file that is just a stub like so

 {% block content %}{% endblock %}

and then set the usemock variable to determine if you will be using the mock data or not.

Hopefully this helps, even though it doesn't really solve the exact problem you are having.

like image 35
Reid Johnson Avatar answered Oct 14 '22 18:10

Reid Johnson