Skip to content

Instantly share code, notes, and snippets.

@daltonrooney
Last active May 22, 2020 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daltonrooney/ab170a14e938a29562d834004ca08436 to your computer and use it in GitHub Desktop.
Save daltonrooney/ab170a14e938a29562d834004ca08436 to your computer and use it in GitHub Desktop.
Useful HTML filters for Timber Twig (widows and markdown support)
<?php
add_filter( 'timber/twig', 'add_to_twig' );
function add_to_twig( $twig ) {
$twig->addFilter( new Timber\Twig_Filter( 'noWidows', 'twigNoWidow' ) );
return $twig;
}
function twigNoWidow($text = "", $numberOfWords = 1, $outputRaw = true ) {
$tags = "a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt";
// Taken from https://github.com/davethegr8/cakephp-typogrify-helper/blob/master/views/helpers/typogrify.php
$regex = "/([^\s])\s+(((<($tags)[^>]*>)*\s*[^\s<>]+)(<\/($tags)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
$string = $text;
for ($i = 0; $i < $numberOfWords; $i++) {
$string = preg_replace($regex, '$1&nbsp;$2', $string);
}
return $string;
}
if ( function_exists('wpmarkdown_markdown_to_html') && function_exists('wpmarkdown_html_to_markdown') ) {
add_filter( 'timber/twig', 'md_add_to_twig' );
// Requires WP-Markdown
// Usage {{post.title|md2html}} {{post.description|html2md}}
function md_add_to_twig( $twig ) {
$twig->addFilter( new Timber\Twig_Filter( 'md2html', 'md2html' ) );
$twig->addFilter( new Timber\Twig_Filter( 'html2md', 'html2md' ) );
return $twig;
}
function md2html($content) {
return wpmarkdown_markdown_to_html($content);
}
function html2md($content) {
return wpmarkdown_html_to_markdown($content);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment