Created
June 7, 2018 20:23
-
-
Save badabingbreda/6a1dfd8240f6df456ad35c6d5c54780c to your computer and use it in GitHub Desktop.
Example code to extend Timber/Twig with custom filters and functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class toolboxTwigExtend { | |
public static function init() { | |
add_filter( 'timber/twig', __CLASS__ . '::add_to_twig' ); | |
} | |
public static function add_to_twig( $twig ) { | |
/* this is where you can add your own functions to twig */ | |
$twig->addExtension(new Twig_Extension_StringLoader()); | |
/** | |
* Template filter for Twig | |
* @usage {{var|whatever(4)}} | |
*/ | |
$twig->addFilter(new Twig_SimpleFilter( 'whatever', __CLASS__ . '::my_whatever' ) ); | |
/** | |
* Dump variable | |
* @usage {{ dumpv( var ) }} | |
*/ | |
$twig->addFunction(new Timber\Twig_Function( 'dumpv', __CLASS__ . '::dump' ) ); | |
/** | |
* Get multiple acf field values | |
* @usage {% set myfields = get_multi_fields( [ 'field1', 'field2' ] ) %} | |
*/ | |
$twig->addFunction(new Timber\Twig_Function( 'get_multi_fields', __CLASS__ . '::get_fields' ) ); | |
return $twig; | |
} | |
/** | |
* Example Filter for Twig | |
* @param [type] $text [description] | |
* @param integer $repeat [description] | |
* @return [type] [description] | |
*/ | |
public static function my_whatever( $text , $repeat = 1 ) { | |
for ( $i = 0; $i < $repeat; $i++ ) { | |
$text .= ' or whatever'; | |
} | |
return $text; | |
} | |
/** | |
* Example Function for Twig | |
* @param [type] $var [description] | |
* @return [type] [description] | |
*/ | |
public static function dump( $var ) { | |
ob_start(); | |
var_dump( $var ); | |
return ob_get_clean(); | |
} | |
/** | |
* Get a bunch of fields for reuse. | |
* @param array $fieldnames [description] | |
* @param integer $postid [description] | |
* @return [type] [description] | |
*/ | |
public static function get_fields( $fieldnames = array() , $postid = 0 ) { | |
if ( is_array( $fieldnames ) && sizeof( $fieldnames ) > 0 ) { | |
foreach ( $fieldnames as $field ) { | |
$return[ "{$field}" ] = get_field( $field , $postid ); | |
} | |
} else if( is_string( $fieldnames ) && $fieldnames !== '' ){ | |
$return[ "{$fieldnames}" ] = get_field( $fieldnames , $postid ); | |
} | |
return $return; | |
} | |
} | |
toolboxTwigExtend::init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment