twig
나뭇 가지 연장
수색…
비고
사용자 정의 필터 / 함수 추가하기
다음은 새 필터 / 함수를 twig
에 추가하는 방법에 대한 몇 가지 예입니다.
Twig_Function을 추가하는 Twig_Function
는 Twig_Filter
와 Twig_Filter
, 그에 따라 키워드를 변경하면됩니다.
<?php
$twig = new Twig_Environment($loader);
/* You can chain a global function */
$twig->addFilter(new Twig_SimpleFilter('floor', 'floor'));
/* You can specify a custom function */
$twig->addFilter(new Twig_SimpleFilter('money', function($value, $currency, $prefix = false, $decimals = 2, $dec_point = "." , $thousands_sep = ",") {
$value = number_format($value, $decimals, $dec_point, $thousands_sep);
if ($prefix) return $currency.' '.$value;
return $value.' '.$prefix;
});
/* You can chain an object's method */
$twig->addFilter(new Twig_SimpleFilter('foo_bar', array($foo, 'bar')));
Twig_Extension 만들기
모든 사용자 정의 함수 / filters / tests / ...를 사용자 정의 Twig_Extension
클래스 내에 그룹화 할 수 있습니다.
ProjectTwigExtension
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('twig_function_name', array($this, 'getTwigFunctionName')),
new Twig_SimpleFunction('twig_function_foo', array($this, 'getTwigFunctionFoo')),
);
}
public function getFilters() {
return array(
new Twig_SimpleFilter('twig_filter_name' , array($this, 'getTwigFilterName')),
new Twig_SimpleFilter('twig_filter_foo' , array($this, 'getTwigFilterFoo')),
);
}
public function getName() {
return 'ProjectTwigExtension';
}
}
나뭇 가지에 등록 연장
$twig = new Twig_Environment($loader);
$twig->addExtension(new ProjectTwigExtension());
공식 문서 에서 더 많은 옵션을 찾을 수 있습니다.
단순 생년월일 필터
어떻게 ...
1 - 확장하는 나뭇 가지 확장 클래스 사용
use \Twig_Extension
class dobToAge extends \Twig_Extension {
2 - getFilters () 메서드를 재정 의하여 적절한 필터 추가
public function getFilters() {
return array(
'age' => new \Twig_Filter_Method($this, 'getAge'),
);
}
3 - 주어진 생년월일을 얻기위한 논리를 추가하십시오.
public function getAge($date)
{
if (!$date instanceof \DateTime) {
// turn $date into a valid \DateTime object or let return
return null;
}
$referenceDate = date('01-01-Y');
$referenceDateTimeObject = new \DateTime($referenceDate);
$diff = $referenceDateTimeObject->diff($date);
return $diff->y;
}
}
그런 다음 필터를 다음과 같이 호출하십시오.
{{ yourDateOfBirthInstance | age }}
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow