laco-agency / seo-behavior
为 Yii2 模型和元标签辅助函数提供 SEO 行为
0.4
2018-10-05 09:20 UTC
Requires
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-09-20 22:53:29 UTC
README
为 Yii2 模型和元标签辅助函数提供 SEO 行为
安装
composer require --prefer-dist laco-agency/seo-behavior
或者添加
"laco-agency/seo-behavior": "*"
到你的 composer.json 的 require 部分。
使用方法
模型
use laco/seo/SeoModelBehavior;
public function behaviors() { return [ [ 'class' => SeoModelBehavior::className(), 'descriptionFromAttribute' => 'teaser', 'metaImageAttribute' => 'image_preview' ] ] }
控制器
use laco/seo/SeoControllerBehavior;
附加行为
public function behaviors() { return [ SeoControllerBehavior::className() ]; }
如果父控制器已经具有行为,您可以像这样附加 SeoControllerBehavior
public function behaviors() { $behaviors = [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [] ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [] ] ]; return array_merge(parent::behaviors(), $behaviors); }
或者像这样
public function init() { $this->attachBehavior('seo', SeoControllerBehavior::className()); }
动作
在动作中使用方法 $this->setMetaTags($model) 并将 $model 作为参数传递;
public function view($slug) { $model = Material::findOne(['slug' => $slug])); $this->setMetaTags($model); }
或者使用这种格式的数组代替模型
[ 'metaTitle' => 'Custom meta title', 'metaDescription' => 'Custom description', 'metaImage' => 'Custom meta image' ]