我在$ config参数中定义了Recaptcha键:
$config['params'] = [
'recaptcha_private' => 'SECRET',
'recaptcha_public' => 'NOT_SECRET'
];
如何将此参数添加到AppAssets?
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $cssOptions = ['rel'=>"stylesheet preload",'as'=>'style'];
public $css = [
/*SOME CSS*/
];
public $js = [
'https://www.google.com/recaptcha/api.js?render=HERE I NEED NOT_SECRET KEY'
];
public $depends = [];
}
您可以像这样在资产捆绑包中覆盖init()
方法
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $cssOptions = ['rel'=>"stylesheet preload",'as'=>'style'];
public $css = [
/*SOME CSS*/
];
public $js = [
'https://www.google.com/recaptcha/api.js?render=',
];
public $depends = [];
public function init()
{
parent::init();
$this->js[0] .= Yii::$app->params['recaptcha_public'];
}
}
[重写parent::init()
的init方法时,请不要忘记调用AssetBundle
。但是此方法以后可能会引起问题,因为在配置中自定义资产捆绑包时,在添加密钥时必须小心。
更安全的变体可能是使用自定义从web.php配置中使用密钥来设置js url。
return [
// ...
'components' => [
'assetManager' => [
'bundles' => [
'app\assets\AppAset' => [ //modify to match your namespace
'js' => [
'https://www.google.com/recaptcha/api.js?render=RECAPTCHA_PUBLIC_KEY',
],
],
],
],
],
];