Last active
May 22, 2020 17:15
-
-
Save daltonrooney/ab170a14e938a29562d834004ca08436 to your computer and use it in GitHub Desktop.
Useful HTML filters for Timber Twig (widows and markdown support)
This file contains 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 | |
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 $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