LoginSignup
15
11

More than 5 years have passed since last update.

Twigで独自の関数を使えるようにする

Last updated at Posted at 2016-04-15

はじめに

Twigはビューなので、ロジックをもたない、もつことができないような仕組みになっています。
原則必要なデータ(変数)のみをビューに渡して、それを表示するのみ。
計算や加工などデータの処理はコントローラやモデル側で行うことが推奨されています。

PHP標準の関数も使えません。Twigテンプレート内でecho()とか書いてもエラーになります。

しかし、ビュー側で関数を扱いたいこともあります。
たとえば、HTMLタグが冗長な表記になってしまうところをヘルパー関数でまとめたい等。

組み込み関数

というように基本的に関数は使いませんが、TwigでもいくつかのFunctionがデフォルトで定義されています。

http://twig.sensiolabs.org/documentation
⇒Twig Reference⇒Functions

下記はTwigにもともと用意されている関数を使うサンプルです。

twig_sample.html.twig
<html>
    <head>
        <title>Function Sample</title>
    </head>
    <body>
        {{ random() }}
        {{ max(1,5,3) }}
        {{ range(1,10)|join('|') }}
    </body>
</html>
twig_sample.php
<?php
require_once 'vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('.');

$twig = new Twig_Environment($loader);

$template = $twig->loadTemplate('twig_sample.html.twig');

echo $template->render([]);
?>

実行してみます。

c:\tmp>php twig_sample.php
<html>
    <head>
        <title>Function Sample</title>
    </head>
    <body>
        1505204978
        5
        1|2|3|4|5|6|7|8|9|10
    </body>
</html>

上記では3つの関数を使いました。

  • random()
  • max()
  • range()

random()はランダムな数値や文字列を返します。
http://twig.sensiolabs.org/doc/functions/random.html

max()は引数で与えられた値の中で最大値を返します。
http://twig.sensiolabs.org/doc/functions/max.html

range()は引数で与えた範囲の数値を「配列」で返します。
http://twig.sensiolabs.org/doc/functions/range.html

注)range()は配列を返すため、range()だけの結果を出力しようとするとエラーになってしまいます。
テンプレートは文字列として出力する必要があるためです。
したがって、ここではjoin()フィルターをつけて、配列の中身を結合して文字列化しています。

自作関数1

今度は自作の関数をTwigで使用してみます。

やり方はいくつかありますが、自作の関数をTwigに渡す必要があります。
そのためにaddFunction()という関数が用意されています。

サンプルはこんな感じです。

twig_sample2.html.twig
<html>
    <head>
        <title>Function Sample2</title>
    </head>
    <body>
        {{ my_function() }}
    </body>
</html>
twig_sample2.php
<?php
require_once 'vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('.');

$twig = new Twig_Environment($loader);

$function = new Twig_SimpleFunction('my_function', function () {
    echo "This is my function!";
});
$twig->addFunction($function);

$template = $twig->loadTemplate('twig_sample2.html.twig');

echo $template->render([]);
?>

実行結果は下記のとおり。
echoした内容が出力されています。

c:\tmp>php twig_sample2.php
<html>
    <head>
        <title>Function Sample2</title>
    </head>
    <body>
        This is my function!
    </body>
</html>

自作関数2

関数を切り出して、引数を受け付けるようにしてみました。

twig_sample3.html.twig
<html>
    <head>
        <title>Function Sample3</title>
    </head>
    <body>
        {{ my_echo("This is my echo!") }}
    </body>
</html>
twig_sample3.php
<?php

function my_echo($val){
    echo $val;
}

require_once 'vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('.');

$twig = new Twig_Environment($loader);

$function = new Twig_SimpleFunction('my_echo', 'my_echo');
$twig->addFunction($function);

$template = $twig->loadTemplate('twig_sample3.html.twig');

echo $template->render([]);
?>

実行結果は下記のとおり。
echoした内容が出力されています。

c:\tmp>php twig_sample3.php
<html>
    <head>
        <title>Function Sample3</title>
    </head>
    <body>
        This is my echo!
    </body>
</html>
15
11
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
15
11