合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
### :-: **视图核心类** ~~~ <?php namespace core; use Twig\Environment; use Twig\Loader\FilesystemLoader; use core\twig\TwigExtension; /** * View 视图类 */ class View { protected $_controller; protected $_action; protected $_assign = array(); function __construct($controller, $action) { $this->_controller = strtolower($controller); $this->_action = strtolower($action); } /** * 视图类 分配变量 * @param $name string * @param $value */ public function assign(string $name, $value) { $this->_assign[$name] = $value; } /** * 视图类 Smarty渲染显示 * @param $name string * @param $path string */ public function render(string $name, string $path = '') { $config['cache'] = BASE_PATH . '/runtime/view'; if (APP_DEBUG === true) { $config['strict_variables'] = false; $config['debug'] = true; } $loader = new FilesystemLoader(BASE_PATH . '/view/' . $this->_controller . '/'); $twig = new Environment($loader, $config); $twig->addExtension(new TwigExtension()); $twig->addGlobal('_GET', $_GET); $twig->addGlobal('_POST', $_POST); $twig->addGlobal('_SESSION',(new Session)->all()); echo $twig->render($name . '.html', $this->_assign ?: []); } } ~~~ ### :-: **自定义标签** core\twig\TwigExtension.php ~~~ <?php namespace core\twig; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; class TwigExtension extends AbstractExtension { /** * NEW 函数 */ public function getFunctions(): array { return [ new TwigFunction('url', [$this, 'url']), new TwigFunction('asset', [$this, 'asset']), ]; } /** * URL 方法 */ function url($url, $param = []): string { return urldecode("/" . strtolower($url) . "?" . http_build_query($param)); } /** * ASSET 方法 */ public function asset($param): string { return "/asset/" . $param; } } ~~~ ~~~