Yii2 Twig not working for page views - yii2

I have installed the yii2-basic-app and installed twig extension, and have made a main.twi layout which is working well.
My page views however that are in the site folder however still have the .php extension and are also php files.
If I rename these to have the .twig extension and put in twig code, the breaks as it is still looking for index.php for the home page, if I rename the .twig back to .php it spits out the twig code into the page.
How can I use twig for page views just like I did for the main.twig layout?
I've done some more googling since I posted the question, and found a similiar question on stackoverflow, this person modified the SiteController and added the .twig extension here, but I also read that it's possible to define the extension in the web.php config but i've been unable to find how to do this.
The contents of my main.twig is:
{{ use('app/assets/AppAsset') }}
{{ register_app_asset() }}
{{ this.beginPage() }}
<!DOCTYPE html>
<html lang="{{app.language}}">
<head>
<meta charset="{{app.charset}}"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{ html.csrfMetaTags() | raw }}
<title>{{ html.encode(this.title) }}</title>
{{ this.head() }}
</head>
<body>
{{ this.beginBody() }}
<div class="wrap">
{{ use('yii/bootstrap') }}
{{ nav_bar_begin({
'brandLabel': app.name,
'brandUrl': app.homeUrl,
'options': [{
'class': 'navbar-inverse navbar-fixed-top',
}],
}) }}
{% set menuItems = [] %}
{% set menuItems = menuItems|merge([
{'label': 'Home', 'url': ['/site/index']},
{'label': 'About', 'url': ['/site/about']},
{'label': 'Contact', 'url': ['/site/contact']},
])
%}
{% if app.user.isGuest == false %}
{% set menuItems = menuItems|merge([
{
'label' : 'logout (' ~ app.user.identity.username ~ ')',
'url' : ['/site/logout'],
'linkOptions' : {'data-method' : 'post'}
}
])
%}
{% else %}
{% set menuItems = menuItems|merge([
{'label' : 'login', 'url' : ['/site/login']},
])
%}
{% endif %}
{{ nav_widget({
'options': {
'class': 'navbar-nav navbar-right',
},
'items': menuItems
}) }}
{{ nav_bar_end() }}
<div class="container">
{{ content | raw }}
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© My Company {{ 'now'|date('Y') }}</p>
<p class="pull-right">{{ Yii.powered() | raw }}</p>
</div>
</footer>
{{ this.endBody() }}
</body>
</html>
{{ this.endPage() }}
This is also my config/web.php file as to how yii and twig is setup.
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'ywLqCkq0cMC-cvfVXiGXFnfu2S41_CbC',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
//'class' => 'yii\web\UrlManager',
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'about' => 'site/about',
'contact' => 'site/contact',
'login' => 'site/login',
],
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
// setting up twig
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => false, // '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
YII_DEBUG ? [ 'debug' => true, ] : [],
],
'extensions' => YII_DEBUG ? [ '\Twig_Extension_Debug', ] : [],
'globals' => [
'html' => '\yii\helpers\Html',
'url' => '\yii\helpers\Url',
'yii' => 'Yii',
],
'uses' => ['yii\bootstrap'],
],
],
],
],
'layout' => 'main.twig',
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'],
];
}
return $config;

// setting up twig
'view' => [
'class' => 'yii\web\View',
'defaultExtension' => 'twig',
// ...
],
https://www.yiiframework.com/doc/api/2.0/yii-base-view#$defaultExtension-detail

Related

RBAC Routes add default route of module to all the routes of project?

If I add this configuration of the cms module to the config file
'cms' => [
'class' => 'yii2mod\cms\Module',
'controllerNamespace' => 'backend\controllers',
'defaultRoute' => '',
'froalaEditorOptions' => [
'clientOptions' => [
'heightMin' => 300,
'theme' => 'dark',
'imageUploadURL' => 'upload-image',
'imageManagerDeleteURL' => 'delete-image',
'imageManagerDeleteMethod' => 'POST',
'imageManagerLoadURL' => 'images'
],
'excludedPlugins' => [
'file',
'emoticons'
]
],
'enableMarkdown' => false
]
It adds the default route of this module to all the routes like this
/cms/site/login /cms/site/index /cms/site/error. Why this is happening and how i can remove this?
If you want to remove the /cms module prefix by default, you can add a global route to backend/config/main.php(If you use advanced templates): '<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'.
for example:
// backend/config/main.php
return [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:[\w-]+>/<action:[\w-]+>' =>'cms/<controller>/<action>'
],
],
];
Access in your bowser: www.xxx.com/site/index, it is forwarded to: /cms/site/index

yii basic app, yii-twig classes being set with 0-class when using nav_bar_begin

I'm using yii as a basic app with the yii-twig extension, and am creating a navigation menu using nav_bar_begin but the class is being set different to how I expected it to, because of this the navigation menu is grey and not black as it should be.
When I view the source code I see this:
<nav id="w0" class="navbar navbar-default" 0-class="navbar-inverse navbar-fixed-top">
<div class="container"><div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w0-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">My Application</a>
</div>
<div id="w0-collapse" class="collapse navbar-collapse">
<ul id="w1" class="navbar-nav navbar-right nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li>login</li>
</ul>
</div>
</div>
The part that isn't being set correctly for my stylesheet is the very first line, where it has class="..." and also 0-class="...".
The styles that are in 0-class should actually of been in class instead.
the contents of my main.twig is:
{{ use('app/assets/AppAsset') }}
{{ register_app_asset() }}
{{ this.beginPage() }}
<!DOCTYPE html>
<html lang="{{app.language}}">
<head>
<meta charset="{{app.charset}}"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{ html.csrfMetaTags() | raw }}
<title>{{ html.encode(this.title) }}</title>
{{ this.head() }}
</head>
<body>
{{ this.beginBody() }}
<div class="wrap">
{{ use('yii/bootstrap') }}
{{ nav_bar_begin({
'brandLabel': app.name,
'brandUrl': app.homeUrl,
'options': [{
'class': 'navbar-inverse navbar-fixed-top',
}],
}) }}
{% set menuItems = [] %}
{% set menuItems = menuItems|merge([
{'label': 'Home', 'url': ['/site/index']},
{'label': 'About', 'url': ['/site/about']},
{'label': 'Contact', 'url': ['/site/contact']},
])
%}
{% if app.user.isGuest == false %}
{% set menuItems = menuItems|merge([
{
'label' : 'logout (' ~ app.user.identity.username ~ ')',
'url' : ['/site/logout'],
'linkOptions' : {'data-method' : 'post'}
}
])
%}
{% else %}
{% set menuItems = menuItems|merge([
{'label' : 'login', 'url' : ['/site/login']},
])
%}
{% endif %}
{{ nav_widget({
'options': {
'class': 'navbar-nav navbar-right',
},
'items': menuItems
}) }}
{{ nav_bar_end() }}
<div class="container">
{{ content | raw }}
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© My Company {{ 'now'|date('Y') }}</p>
<p class="pull-right">{{ Yii.powered() | raw }}</p>
</div>
</footer>
{{ this.endBody() }}
</body>
</html>
{{ this.endPage() }}
This is also my config/web.php file as to how yii and twig is setup.
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'ywLqCkq0cMC-cvfVXiGXFnfu2S41_CbC',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
//'class' => 'yii\web\UrlManager',
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'about' => 'site/about',
'contact' => 'site/contact',
'login' => 'site/login',
],
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
// setting up twig
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => false, // '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
YII_DEBUG ? [ 'debug' => true, ] : [],
],
'extensions' => YII_DEBUG ? [ '\Twig_Extension_Debug', ] : [],
'globals' => [
'html' => '\yii\helpers\Html',
'url' => '\yii\helpers\Url',
'yii' => 'Yii',
],
'uses' => ['yii\bootstrap'],
],
],
],
],
'layout' => 'main.twig',
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*'],
];
}
return $config;
You have a error in widget configuration. Replace
'options': [{
'class': 'navbar-inverse navbar-fixed-top',
}],
with
'options': {
'class': 'navbar-inverse navbar-fixed-top',
},

Yii2 i18n not working

I'm having trouble into working with i18n in Yii2 advanced template.
Translation is not working!
I have run these commands in yii2 project root directory.
Official link
./yii message/config --languages=de,it,fr --messagePath=messages i18n.php
./yii message/extract i18n.php
It generate i18n.php under project root directory and de,it,fr directories under message directory.
in de directory I have create new file app.php with this content:
<?php
return [
'Home' => 'Home de',
'Getting Started' => 'Getting Started de',
];
In common/config/main.php
// set target language to be English
'language' => 'en-US',
// set source language to be English
'sourceLanguage' => 'en-US',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => realpath(dirname(__FILE__).'/../../').'messages',
//'sourceLanguage' => 'en-US',
//'fileMap' => [
//'app' => realpath(dirname(__FILE__).'/../../').'app.php',
// 'app/error' => 'error.php',
//],
],
],
],
]
View:
<?= Yii::t('app','Home')?>
<?= Yii::t('app','Getting Started') ?>
How I can get it working?
You can set target language in your config:
...
'language' => 'ru-RU',
...
If 'sourceLanguage' => 'en-US', yii will translate from en-US to ru-RU.
And config i18n component will be:
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/translation',
'fileMap' => [
'app' => 'app.php',
],
],
],
],
Directory structure is:
- translation
- ru-RU
- app.php
Example in file app.php
return [
'Home' => 'abcxyz',
'source key' => 'translate to russian',
];
Hope it helpful.
Goodluck and have fun!
If you are using advanced template,edit i18n.php
'sourcePath' =>__DIR__. DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
which will create message folder inside common folder.
And in config file
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
....
]
and in view use as you have.Good Luck

How can I use Yii2 Glide

I already use yii2-file-kit. And now I want to resize my thumbnail by glide but I'be got error in log
"NetworkError: 500 Internal Server Error - http://storage.local/cache/1/iApQj79NQCji2TWsLZppiCQ8lbdgAPBz.jpg?w=100"
Here is my config
'components' => [
'cache' => [
'class' => 'yii\caching\DummyCache',
],
'fileStorage' => [
'class' => '\trntv\filekit\Storage',
'baseUrl' => '#storageUrl/source',
'filesystem' => [
'class' => 'common\components\filesystem\LocalFlysystemBuilder',
'path' => '#storage/web/source'
],
'as log' => [
'class' => 'common\behaviors\FileStorageLogBehavior',
'component' => 'fileStorage'
]
],
'glide' => [
'class' => 'trntv\glide\components\Glide',
'sourcePath' => '#storage/web/source',
'cachePath' => '#storage/cache',
'urlManager' => 'urlManagerStorage',
'maxImageSize' => 4000000,
'signKey' => 'pe4AJmRcBFbXfZvsk93VN'
],
And in my view
<?= Html::img(
Yii::$app->glide->createSignedUrl([
'glide/index',
'path' => $model->productAttachments[0]->path,
'w' => 100
], true),
['class' => 'article-thumb img-rounded pull-left']
) ?>
I just look at Starter-Kit config and there is the same config as I see. storage config are the same as yii2-starter-kit
Can you show debug for more information. Or you can output image by
Url::base(true).'/glide?path='.$path.'&w='.$w.'&h='.$h.'&fit=crop';

application configuration file path of yii2

I installed yii2 and then added gii to yii2 from this link.
return [
'bootstrap' => ['gii'],
'modules' => [
'gii' => 'yii\gii\Module',
// ...
],
// ...
];
I want to plce this code in application configuration file where it is located?
Application configuration file reside in: project_name/config/web.php
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class'=>'yii\gii\Module',
'allowedIPs'=>['127.0.0.1','192.168.1.*'],
];
You will find a file web.php which is in in the config folder located at your root app folder, the file will contain something like the following:
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'name' => 'My Cool App',//If this line exists change it to your new app name otherwise add it.
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '_4wmrZYaMY7joBAFHrXKpEIFvs9m9S_I',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if(YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Notice I've added a line: 'name' => 'My Cool App',
Hope this helps.