{"id":1011,"date":"2019-12-08T20:22:14","date_gmt":"2019-12-08T13:22:14","guid":{"rendered":"https:\/\/lab.wptips.dev\/?p=1011"},"modified":"2020-05-04T22:35:39","modified_gmt":"2020-05-04T15:35:39","slug":"global-var-n-filters-in-timber","status":"publish","type":"post","link":"https:\/\/pixelstudio.id\/blog\/global-var-n-filters-in-timber\/","title":{"rendered":"Adding Global Variables &#038; Custom Filters in Timber"},"content":{"rendered":"\n<blockquote class=\"wp-block-quote\"><p><strong>Timber<\/strong> is a plugin to allow separation between PHP and HTML files.  <a href=\"https:\/\/pixelstudio.id\/blog\/what-is-timber-library\/\">Click here<\/a> for introduction.<\/p><\/blockquote>\n\n\n\n<p>Both Global variable and custom filter can be added by extending <code>TimberSite<\/code> class.<\/p>\n\n\n\n<p>The class outline is as follow: <\/p>\n\n\n\n<pre title=\"code\/timber.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php line-numbers\">class MyTimber extends TimberSite {\n\n  function __construct() {\n    add_filter( 'timber_context', [$this, 'add_to_context'] );\n    add_filter( 'get_twig', [$this, 'add_to_twig'] );\n    parent::__construct();\n  }\n  \n  \/\/ Add Global variable\n  function add_to_context( $context ) {\n    \/\/ ...\n    return $context;\n  }\n\n  \/\/ Add Custom filter\n  function add_to_twig( $twig ) {\n    \/\/ ...\n    return $twig;\n  }\n}\n\nnew MyTimber(); \/\/ call the class<\/code><\/pre>\n\n\n\n<p>Don&#8217;t forget to require it in your Functions file:<\/p>\n\n\n\n<pre title=\"functions.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">...\nrequire_once 'code\/timber.php';\n...<\/code><\/pre>\n\n\n\n<p>Let&#8217;s discuss each section above in more detail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Global Variable (line 10)<\/h2>\n\n\n\n<p>Anything added into <code>$context<\/code> array will become global variables and accessible in all views.<\/p>\n\n\n\n<p>The example below shows the values that are commonly set as global variables: <\/p>\n\n\n\n<pre title=\"code\/timber.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">function add_to_context( $context ) { \n  \/\/ Site's settings like site.title\n  $context['site'] = $this; \n  $context['home_url'] = home_url();\n\n  \/\/ Menu - Timber stored it as an array so you can loop it and write custom markup\n  $context['nav'] = new TimberMenu( 'main-nav' );\n  \n  \/\/ Link to the image inside your theme\n  \/\/ Example:   &lt;img src=\"{{ images }}\/logo.svg\">\n  $context['images'] = get_template_directory_uri() . '\/images';\n  \n  \/\/ Footer Widget - for post widget, no need to be global\n  $context['footer_widgets'] = Timber::get_widgets( 'footer_widgets' );\n\n  \/\/ ACF Options Page, if you have one\n  if( function_exists( 'acf_add_options_page' )) {\n    $context['options'] = get_fields( 'options' );\n  }\n\n  \/\/ WooCommerce, if installed\n  if( class_exists('WooCommerce') ) {\n    global $woocommerce;\n    $context['woo'] = $woocommerce;\n  }\n\n  return $context;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Custom Filter (line 16)<\/h2>\n\n\n\n<p>We use <code>addFilter<\/code> function and pass in a special class. The class takes the filter name and a function that handles the value.<\/p>\n\n\n\n<p>It&#8217;s quite confusing. Will be clearer if you take a look at this example below:<\/p>\n\n\n\n<pre title=\"code\/timber.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">function add_to_twig( $twig ) {\n  $twig->addFilter( new Twig_SimpleFilter( 'my_example', [$this, 'filter_my_example'] ) );\n  $twig->addFilter( new Twig_SimpleFilter( 'my_example2', [$this, 'filter_my_example2'] ) );\n  return $twig;\n}\n\n\/**\n * Basic custom filter\n *\n * {{ post.content | my_example }}\n *\/\nfunction filter_my_example( $value ) {\n  \/\/ do something\n  return $value;\n}\n\n\/**\n * Has passed argument\n *\n * {{ post.content | my_example2( 'arg' ) }}\n *\/\nfunction filter_my_example2( $value, $arg ) {\n  \/\/ do something\n  return $value;\n}<\/code><\/pre>\n\n\n\n<p>Remember that the filter functions are still part of <code>MyTimber<\/code> class.<\/p>\n\n\n\n<div class=\"wp-block-button aligncenter\"><a class=\"wp-block-button__link has-background has-green-background-color\" href=\"https:\/\/gist.github.com\/hrsetyono\/7bf65b9a8e3239983f0f11c985338295\" target=\"_blank\" rel=\"noreferrer noopener\">See the Full Code in Github<\/a><\/div>\n\n\n\n<hr class=\"wp-block-separator is-style-dots\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Use Global variable <strong>only on things that appear on all pages<\/strong> as it can slow down your site. From my experience, ACF Options is very slow, but it doesn&#8217;t matter when you use a cache plugin.<\/p>\n\n\n\n<p>For Custom filter, try not to overuse it. Most of the time, you can avoid using the filter by processing your value in the PHP file first.<\/p>\n\n\n\n<p>If you are interested to learn more about Timber, check out  the following:<\/p>\n\n\n\n<ul><li><a href=\"https:\/\/github.com\/hrsetyono\/timber-basic-theme\">Basic Theme<\/a> &#8211; Plain Timber theme intended for teaching you the rope about Timber.<\/li><li><a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/github.com\/timber\/starter-theme\" target=\"_blank\">Starter Theme<\/a> &#8211; Fully-featured theme built with Timber.<\/li><li><a href=\"https:\/\/www.upstatement.com\/timber\/\">Timber Official Docs<\/a><\/li><li><a rel=\"noreferrer noopener\" aria-label=\"Twig Language Docs (opens in a new tab)\" href=\"https:\/\/twig.symfony.com\/\" target=\"_blank\">Twig Language Docs<\/a><\/li><\/ul>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Let us know if you have trouble implementing global variable \ud83d\ude42<\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>Every WordPress site built with Timber needs Global variable because there is always some data that appears in every page like Menu and Widgets.<\/p>\n","protected":false},"author":1,"featured_media":1030,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[31,24],"class_list":["post-1011","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-timber","tag-php","tag-timber"],"blocksy_meta":{"page_structure_type":"default","page_enable_vertical_spacing":"yes","has_hero_section":"default","hero_section":"type-1","hero_alignment1":"left","hero_alignment2":"center","hero_height":"230px","page_title_bg_type":"color","f6a784d1160a103eca9a897d66d6219e":"","custom_hero_background":{"attachment_id":null},"parallax":{"desktop":false,"tablet":false,"mobile":false},"93d6ee4519d10319b7cac50cf3963759":"","single_meta_elements":{"author":true,"date":true,"categories":true,"comments":true,"updated":false,"tags":false},"has_meta_label":"yes","date_format_source":"custom","single_meta_date_format":"M j, Y","d36908e3fd37eb3e72e5cc838cb8efd9":"","page_excerpt_visibility":{"desktop":true,"tablet":true,"mobile":false},"pageTitleFont":{"family":"Default","variation":"Default","size":{"desktop":"32px","tablet":"30px","mobile":"25px"},"line-height":"1.3","letter-spacing":"CT_CSS_SKIP_RULE","text-transform":"CT_CSS_SKIP_RULE","text-decoration":"CT_CSS_SKIP_RULE"},"pageTitleFontColor":{"default":{"color":"var(--paletteColor4)"}},"pageMetaFont":{"family":"Default","variation":"n6","size":{"desktop":"12px","tablet":"12px","mobile":"12px"},"line-height":"1.3","letter-spacing":"CT_CSS_SKIP_RULE","text-transform":"uppercase","text-decoration":"CT_CSS_SKIP_RULE"},"pageMetaFontColor":{"default":{"color":"CT_CSS_SKIP_RULEDEFAULT"},"hover":{"color":"CT_CSS_SKIP_RULEDEFAULT"}},"pageExcerptFont":{"family":"Default","variation":"n5","size":"CT_CSS_SKIP_RULE","line-height":"CT_CSS_SKIP_RULE.65","letter-spacing":"CT_CSS_SKIP_RULE","text-transform":"CT_CSS_SKIP_RULE","text-decoration":"CT_CSS_SKIP_RULE"},"pageExcerptColor":{"default":{"color":"CT_CSS_SKIP_RULEDEFAULT"}},"pageTitleOverlay":{"default":{"color":"rgba(41, 51, 60, 0.2)"}},"pageTitleBackground":{"default":{"color":"#EDEFF2"}},"d8ea89fe99313b066ceed163d348ff1f":"","1ca24f6a3445c8089c5369e124f217e3":"","00d94a0d344ce087d32847e23d8ef4a6":"","ff2def955ea3b475068da28ef4b0747a":"","3851fa7e9edf4f665037974f6a68c181":"","e176c64c1c2abd4b31aa16baf5eeba16":"","afd0089da7d369daca431a35cf1b1258":"","e551842b203d0a8d07bbf1b91bb4ef45":"","bd4621d1da0506594935461ce6f4cc1b":""},"_links":{"self":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/1011","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/comments?post=1011"}],"version-history":[{"count":10,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/1011\/revisions"}],"predecessor-version":[{"id":1036,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/1011\/revisions\/1036"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/media\/1030"}],"wp:attachment":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/media?parent=1011"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/categories?post=1011"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/tags?post=1011"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}