Created
November 9, 2015 09:54
-
-
Save Leotomas/c36d18be49aa4da72fed to your computer and use it in GitHub Desktop.
Render Wordpress Shortcodes with Twig
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 | |
/** | |
* Renders the view templates using Twig | |
* @author Leo | |
*/ | |
namespace stt\Framework; | |
class View { | |
/** | |
* @param string $view the template view | |
* @param array $data the var sent to the view | |
* @param bool|false $debug debug enabled ? | |
*/ | |
static public function render($view, $data, $debug = false) { | |
$template_path = get_template_directory(); | |
$loader = new \Twig_Loader_Filesystem(''.$template_path.'/Views/'); | |
$settings = array( | |
'cache' => $template_path.'.twig-cache', | |
'debug' => $debug, | |
'autoescape' => false | |
); | |
$twig = new \Twig_Environment($loader, $settings); | |
if ($settings['debug']) { | |
$twig->addExtension(new \Twig_Extension_Debug()); | |
} | |
//first we get the view's HTML | |
ob_start(); | |
echo $twig->render($view, $data); | |
$html = ob_get_contents(); | |
ob_end_clean(); | |
//force shortcode generation from rendered html | |
self::doShortcodesAndRender($html); | |
} | |
/** | |
* @param $view | |
* @param $data | |
* | |
* @return string | |
*/ | |
static public function store($view, $data) { | |
ob_start(); | |
static::render($view, $data); | |
$output = ob_get_contents(); | |
ob_end_clean(); | |
return $output; | |
} | |
/** | |
* @param $html | |
* | |
* @return mixed | |
*/ | |
static protected function doShortcodesAndRender($html) | |
{ | |
$i=0; | |
preg_match_all("/\[[^\]]*\]/", $html, $raw_shortcodes); | |
if(!empty($raw_shortcodes[0])) { | |
foreach($raw_shortcodes[0] as $key=>$raw_shortcode) { | |
$i++; | |
$gen_shortcode[$i] = do_shortcode($raw_shortcode); | |
$render = str_replace($raw_shortcode, $gen_shortcode[$i], $html); | |
} | |
echo $render; | |
} else { | |
echo $html; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment