php - yii2 如何用 "view"中的默认元标记替换 "layout"中的自定义元标记

标签 php html yii2

我想为主模板布局放置默认的元数据描述标签。

在很多情况下,我需要用 View 中的自定义数据替换默认的元标记,例如描述和关键字。

我试过:

$this->registerMetaTag

在我需要自定义元标记的 View 中,我也在主布局中使用了它。

我想如果我将元标记与它们的 id 或名称一起使用,它会被替换,但结果显示重复的元标记,例如

<meta id="main_index" name="Description" content="my default content added by layout.">


<meta id="main_index" name="Description" content="my customized content added by the view"></head>

什么是提供默认描述标签的最佳方式,但每当我调用 $this->registerMetaTag

时都可以通过 View 进行自定义

最佳答案

这是我的解决方案,在没有冗余 Controller 的情况下要简单得多。 您只需在应用参数中定义默认标签并在 View 中覆盖它们即可。

config/params.php

<?php
return [
    'adminEmail' => 'admin@example.com',
    'og_title' => ['property' => 'og:title', 'content' => 'title'],
    'og_description' => ['property' => 'og:description', 'content' => 'description'],
    'og_url' => ['property' => 'og:url', 'content' => '/'],
    'og_image' => ['property' => 'og:image', 'content' => 'image']
];

views/layouts/main.php

<?php
    $this->registerMetaTag(Yii::$app->params['og_title'], 'og_title');
    $this->registerMetaTag(Yii::$app->params['og_description'], 'og_description');
    $this->registerMetaTag(Yii::$app->params['og_url'], 'og_url');
    $this->registerMetaTag(Yii::$app->params['og_image'], 'og_image');
?>

现在,如果我需要设置自定义标签,我会在我的 View 中覆盖参数

views/site/index.php

<?php
    Yii::$app->params['og_title']['content'] = 'custom title';
    Yii::$app->params['og_description']['content'] = 'custom desc';
    Yii::$app->params['og_url']['content'] = '/new/url';
    Yii::$app->params['og_image']['content'] = 'image.jpg';
?>

关于php - yii2 如何用 "view"中的默认元标记替换 "layout"中的自定义元标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171328/

相关文章:

PHP 和 MySQL 时区,同时支持用户定义的时区

php - 在 PHP 文件中查找所有源硬编码字符串 - 翻译目的

php - 将 UL 转换为样式化的 SELECT

java - Html 特殊字符和 Javascript

javascript - 几秒钟后显示/隐藏 HTML 移动按钮

php - 如何使用 Omnipay 退款

javascript - 是否有用转义序列替换 xml 特殊字符的 js 函数?

php - Yii2 redis 缓存优于文件缓存

php - 如何将总计添加到 yii2 GridView 的底部

php - 如何在 yii2 的 AndWhere 中使用嵌套条件