我想为每个视图提供这样的脚本标签
<script type="application/ld+json">
/****** my code
</script>
跟 $this->注册Js(....)
我得到这种代码:
<script>jQuery(function ($) {
.....
});</script>
如何添加不同的类型以及如何删除jQuery..?
默认情况下,registerJs()
正在使用$position = View::POS_READY
,而这个是自动注册jQuery资产。如果您不希望这样做,可以使用:
registerJs($js, yiiwebView::POS_HEAD)
- 将JS放在头部registerJs($js, yiiwebView::POS_BEGIN)
- 将JS放在身体部位的开头registerJs($js, yiiwebView::POS_END)
- 将JS放在身体部位的末尾
不幸的是,所有这些都会在标准<script>
标记中添加您的脚本,而不添加类型。
为此,您必须手动添加它,方法是自己放置<script...>
或在视图或布局文件中调用yiihelpersHtml::script($js, ['type' => 'application/ld+json'])
。
我在布局中使用它。使用块允许我将其替换为其他页面中的其他 schema.org。
<?= Html::script(isset($this->blocks['schema'])
? $this->blocks['schema']
: yiihelpersJson::encode([
'@context' => 'https://schema.org',
'@type' => 'WebSite',
'name' => Yii::$app->name,
'image' => $this->image,
'url' => $this->url,
'descriptions' => $this->description,
'author' => [
'@type' => 'Organization',
'name' => Yii::$app->name,
'url' => Yii::$app->homeUrl,
'telephone' => Yii::$app->params['phone'],
]
]), [
'type' => 'application/ld+json',
]) ?>
只需使用 Html::script($js, $options)。
考虑使用 Json::encode() 以避免在 PHP 中编写 JS 文件。这样对我来说更漂亮,并且还可以使变量 插值更容易。
在此示例中,您会看到很多
$this->image|description|url
因为我正在使用 https://github.com/daxslab/yii2-taggedview 来扩展 yii\web\View 具有更多属性,以使 Opengraph 自动化 和推特卡片标签生成。