zoukankan      html  css  js  c++  java
  • YII2 随笔 视图最佳实践

    • yiiaseController::render(): 渲染一个 视图名 并使用一个 布局 返回到渲染结果。
    • yiiaseController::renderPartial(): 渲染一个 视图名 并且不使用布局。
    • yiiwebController::renderAjax(): 渲染一个 视图名 并且不使用布局, 并注入所有注册的JS/CSS脚本和文件,通常使用在响应AJAX网页请求的情况下。
    • yiiaseController::renderFile(): 渲染一个视图文件目录或 别名下的视图文件。
    • yiiaseController::renderContent(): renders a static string by embedding it into the currently applicable layout. This method is available since version 2.0.1.

    例如:namespace appcontrollers; use Yii; use appmodelsPost; use yiiwebController; use yiiwebNotFoundHttpException; class PostController extends Controller { public function actionView($id) { $model = Post::findOne($id); if ($model === null) { throw new NotFoundHttpException; } // 渲染一个名称为"view"的视图并使用布局 return $this->render('view', [ 'model' => $model, ]); } }

    嵌套布局

    有时候你想嵌套一个布局到另一个,例如,在Web站点不同地方,想使用不同的布局, 同时这些布局共享相同的生成全局HTML5页面结构的基本布局,可以在子布局中调用 yiiaseView::beginContent() 和yiiaseView::endContent() 方法,如下所示:

    <?php $this->beginContent('@app/views/layouts/base.php'); ?>
    
    ...child layout content here...
    
    <?php $this->endContent(); ?>

    调用 yiiaseView::beginBlock() 和 yiiaseView::endBlock() 来定义数据块, 使用 $view->blocks[$blockID] 访问该数据块, 其中 $blockID 为定义数据块时指定的唯一标识ID。

    如下实例显示如何在内容视图中使用数据块让布局使用。

    首先,在内容视图中定一个或多个数据块:

    ...
    
    <?php $this->beginBlock('block1'); ?>
    
    ...content of block1...
    
    <?php $this->endBlock(); ?>
    
    ...
    
    <?php $this->beginBlock('block3'); ?>
    
    ...content of block3...
    
    <?php $this->endBlock(); ?>


         最佳实践

    视图负责将模型的数据展示用户想要的格式,总之,视图

    • 应主要包含展示代码,如HTML, 和简单的PHP代码来控制、格式化和渲染数据;
    • 不应包含执行数据查询代码,这种代码放在模型中;
    • 应避免直接访问请求数据,如 $_GET, $_POST,这种应在控制器中执行, 如果需要请求数据,应由控制器推送到视图。
    • 可读取模型属性,但不应修改它们。

    为使模型更易于维护,避免创建太复杂或包含太多冗余代码的视图, 可遵循以下方法达到这个目标:

    • 使用 布局 来展示公共代码(如,页面头部、尾部);
    • 将复杂的视图分成几个小视图, 可使用上面描述的渲染方法将这些小视图渲染并组装成大视图;
    • 创建并使用 小部件 作为视图的数据块;
    • 创建并使用助手类在视图中转换和格式化数据。
  • 相关阅读:
    ACM-ICPC(10/21)
    ACM-ICPC (10/20)
    ACM-ICPC (10/19)
    ACM-ICPC (10/17)
    ACM-ICPC (10/16) Codeforces Round #441 (Div. 2, by Moscow Team Olympiad)
    ACM-ICPC (10/15) Codeforces Round #440 (Div. 2, based on Technocup 2018 Elimination Round 2)
    ACM-ICPC (10/14)
    战神CPU计算机硬件组装
    ACM-ICPC (10/12)
    ACM-ICPC (10/11)
  • 原文地址:https://www.cnblogs.com/chuanqideya/p/6119188.html
Copyright © 2011-2022 走看看