0

I'm trying to implement a Webpack environment on my Craft 3 projects. In order to dynamically call my hashed resources I'm outputting the in a manifest.json file and importing it into my template.

manifest.json

{"app":["js/app3bfb132e4187389fccd4.js","css/app53079ca4a05210b4af0c.css"],"vendor":"js/vendor49171fe3f01c19da9296.js"}

index.twig

{% set manifest %}
    {% include './manifest.json' %}
{% endset %}

The output of that variable is a string. Is there anyway to encode it so that the variables are accessible/printable using only Twig? (Using {{ manifest.app }} for example)

brunouno
  • 595
  • 7
  • 23

1 Answers1

2

You have to decode the JSON first. I would suggest one of the two approaches:

  • Create custom manifest function for Twig which will return decoded manifest object
  • or create json_decode filter for Twig, decode included json content and use it

manifest function

<?php

namespace App\Twig;

class ManifestExtension extends \Twig_Extension
{
    private $manifestFile;

    public function __construct($manifestFile)
    {
        $this->manifestFile = $manifestFile;
    }

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('manifest', array($this, 'manifest')),
        );
    }

    public function manifest()
    {
        $content = file_get_contents($this->manifestFile);

        return json_decode($content);
    }
}

You can register it as a service in services.yml providing path to the manifest.json file.

App\Twig\ManifestExtension:
    class: 'App\Twig\ManifestExtension'
    arguments: ['%kernel.project_dir%/../public/manifest.json']
    tags: [twig.extension]

Usage:

{% set manifest = manifest() %}

json_decode filter

It's already been covered here:

Decoding JSON in Twig

Usage:

{% set manifest %}
    {% include './manifest.json' %}
{% endset %}

{% set manifest = manifest | json_decode %}
MakG
  • 1,254
  • 9
  • 14