Markdown Filter for PHP’s Timber/Twig Templating  Engine

Parse Markdown in Timber/Twig templates with this custom twig filter/extension.

Markdown is a wonderful way to write content on the web, it’s what I use to write every blog article you see here on kevinleary.net. While working with Upstatement’s Timber plugin I came across a situation where I wanted to provide Markdown support for custom field content in a custom WordPress theme.

Timber provides a get_twig filter hook that can be used to add custom Twig filters. Using this we can add a Markdown filter that will allow us to parse Markdown syntax for any value in our *.twig files.

Twig Filter for Timber

First you’ll need to include the PHP Parsedown library in your project. Download and include Parsedown.php in your theme or plugin, and then use the following class to define a Twig markdown filter that can be used like this: {{ var | markdown }}.

/**
 * Twig Markdown Filter 
 * 
 * Extension for WordPress Timber plugin that support processing 
 * markdown with {{ var | markdown }}.
 */
if ( ! class_exists( 'Timber_Twig_Markdown_Filter' ) && class_exists( 'Timber' ) && class_exists( 'Parsedown' ) ) :

class Timber_Twig_Markdown_Filter {

    /**
     * Constructor
     */
    public function __construct( ) {
        add_filter( 'get_twig', array( $this, 'define_filter' ) );
    }


    /**
     * Filter Definition
     */
    public function define_filter( $twig ) {
        $twig->addFilter( new Twig_SimpleFilter( 'markdown', array( $this, 'parse_markdown' ) ) );

        return $twig;
    }

    /**
     * Markdown Parser
     */
    public function parse_markdown( $text ) {
        $parser = new Parsedown();

        return $parser->text( $text );
    }
}

new Timber_Twig_Markdown_Filter();

endif;

Parsedown is fast and does the job well in PHP, but you don’t have to use it. Any PHP based markdown parser will work, just adjust the parsing method in parse_markdown if you want to use something different. Matthew Spencer outlines another approach that uses Jetpack’s Markdown parser. If you like Jetpack (I don’t) then this may be a better option to use if you already have it installed.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.