Skip to content

Instantly share code, notes, and snippets.

@chabibnr
Last active October 3, 2017 03:18
Show Gist options
  • Save chabibnr/8b57d57dea2fcc8632e91e6f7995f9a0 to your computer and use it in GitHub Desktop.
Save chabibnr/8b57d57dea2fcc8632e91e6f7995f9a0 to your computer and use it in GitHub Desktop.
<?php
namespace app\components;
use yii\web\View;
/**
* Class Controller
* @package app\components
* @author chabib nurozak <chabibdev@gmail.com>
* @version 1
*/
class Controller extends \yii\web\Controller
{
/**
* @param string $view
* @param array $params
* @return string
*/
public function render($view, $params = [])
{
$content = $this->getView()->render($view, $params, $this);
$content = $this->getScript($content);
$content = $this->getStyle($content);
return $this->renderContent($content);
}
/**
* @param string $content
* @return mixed
*/
protected function getScript($content){
$scripts = $this->getStringByTag('script', $content);
$view = $this->getView();
foreach ($scripts as $script){
if(!empty($script)) {
$view->registerJs($script, View::POS_END);
}
}
return $this->removeStringByTag('script', $content);
}
/**
* @param string $content
* @return mixed
*/
protected function getStyle($content){
$styles = $this->getStringByTag('style', $content);
$view = $this->getView();
foreach ($styles as $style){
if(!empty($style)) {
$view->registerCss($style);
}
}
return $this->removeStringByTag('style', $content);
}
/**
* @param string $tagName
* @param string $string
* @return mixed
*/
protected function getStringByTag($tagName, $string){
preg_match_all("/<{$tagName}>(.*?)<\/$tagName>/s", $string, $matches);
return $matches[1];
}
/**
* @param string $tagName
* @param string $string
* @return mixed
*/
protected function removeStringByTag($tagName, $string){
return preg_replace("/<{$tagName}>(.*?)<\/$tagName>/s",'', $string);
}
}
controller dengan extends yii\web\Controller
======================================
<?php
$js = <<<JS
new Vue({
data:{},
methods: {}
})
JS;
$this->registerJs($js, \yii\web\View::POS_END);
?>
controller dengan extends app\components\Controller
======================================
<script>
new Vue({
data: {},
methods:{},
mounted:{}
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment