2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

twigでjsonを出力する

Posted at

twig内で関数から受け取った値がjsonデータだったのでそのまま出力できないので対応策を調べた。

出力するためにはdecodeしてあげないといけない。
そのために独自関数を実装した。

jsonDecodeTwigExtension.php

namespace Customize\Twig\Extension;

use Twig\Extension\AbstractExtension;

class jsonDecodeTwigExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [
            new \Twig_Filter('json_decode', [$this, 'jsonDecodeFilter']),
        ];
    }

    /**
     * @param  null  $json
     *
     * @return mixed|null
     */
    public function jsonDecodeFilter($json = null)
    {
        if (! $json) {
            return null;
        }

        return json_decode($json, true);
    }
}

以下のようなjsonがあるとする。

price.json

{
	"min": 5500,
	"max": 121000,
}

こうやって出力する。

price.twig
{% set price = price | json_decode %}
{{ prices.min }}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?