Giter Site home page Giter Site logo

yiisoft / yii2-twig Goto Github PK

View Code? Open in Web Editor NEW
137.0 29.0 61.0 9.87 MB

Yii 2 Twig extension.

Home Page: http://www.yiiframework.com

License: BSD 3-Clause "New" or "Revised" License

PHP 93.76% Makefile 1.44% Twig 4.80%
yii yii2 twig template-engine hacktoberfest

yii2-twig's People

Contributors

antgubarev avatar arhell avatar bwoester avatar cebe avatar creocoder avatar crtlib avatar egorpromo avatar ext4yii avatar gevik avatar gonimar avatar kartik-v avatar klimov-paul avatar koxu1996 avatar lancecoder avatar larryullman avatar lucianobaraglia avatar mohorev avatar pmoust avatar qiangxue avatar ragazzo avatar resurtm avatar rinatio avatar samdark avatar schmunk42 avatar sensorario avatar slavcodev avatar softark avatar suralc avatar tarasio avatar tonydspaniard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-twig's Issues

using set to set the page title does not work

l have a layout named v1.twig

<html>
<head>
<title>{{ this.title|e}}</title>
</head>
<body>
{% block content %}
{# content placeholder #}
{% endblock content %}
</body>
</html>

When I want to render a view,I write a index.twig file like this:

{% extends 'layouts/v1.twig' %}
{% block content %}
{{ set(this,'title','titleName') }}
my content
{% endblock content %}

but the title was not changeed when the page rendered.
I think maybe this problem caused by the render order,it will render the layout v1.twig' first and thenindex.twig,when it renders v1.twig,it can not get the value of title set in theindex.twig`,how can solve this problem or any other advice?

Error with includes using twig templates in yii2 modules

I'm trying to use twig templates withing a module of yii, but I have problems with the base templates path. I can explain the error better with an example:

I have a module. Then I'm loading this module in my main app.

In the module templates, I have some "partials". So, For example, I have "index.twig" and "_header.twig". In the template "index.twig" I want to render the partial "header.twig"

The directory of the module looks like this:

modules
- mymoduleid
- - controllers
- - views 
- - - index.twig
- - - _header.twig

This is the file "index.twig"

...
{% include "_header.twig" %}
...

When I try to render that template, I'm getting an error beacuse twig can't find that template.

In the other hand, If I try to do this render with php templates, it works like a charm:

...
<?= $this->render('_form.twig') ?>
...

The TwigRenderer is trying to find the partial in the "app" path, instead of in the "module" path...

Any ideas?

Thanks!

Use the method in the template error

我的配置

'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'Url' => ['class' => '\yii\helpers\Url'],
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                ],
            ],

在twig模板使用Url的方法时,
{{ Url.to(['site/home']) }}
报错:

Twig_Error_Runtime
An exception has been thrown during the rendering of a template ("call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object").
Caused by: yii\base\ErrorException
call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object
in /var/www/yii-admin/vendor/yiisoft/yii2-twig/ViewRendererStaticClassProxy.php at line 60

查了一下,是因为传入call_user_func_array的参数为: [['class' => '\yii\helpers\Url' ], 'base']

我修改了:vendor\yiisoft\yii2-twig\ViewRenderer.php 第272行,
$value = new ViewRendererStaticClassProxy($value);
改为
$value = new ViewRendererStaticClassProxy($value['class']);

就可以了。
如果修改globals为以下配置也可以实现

        'globals' => [
                        'Url' => '\yii\helpers\Url',
                        'html' => '\yii\helpers\Html',
                    ],

是不是修改配置比较好?

Error in docs in Template Syntax -> URLs

What steps will reproduce the problem?

Need to read https://github.com/yiisoft/yii2-twig/blob/master/docs/guide/template-syntax.md
Chapter URLs

What's expected?

<a href="{{ path(['blog/view'], {'alias' : post.alias}) }}">{{ post.title }}</a> <a href="{{ url(['blog/view'], {'alias' : post.alias}) }}">{{ post.title }}</a>
it`s not correct

What do you get instead?

Correct is
<a href="{{ path('blog/view', {'alias' : post.alias}) }}">{{ post.title }}</a> <a href="{{ url('blog/view', {'alias' : post.alias}) }}">{{ post.title }}</a>
without [ ]

Additional info

Q A
Yii vesion 2.0.12
PHP version 5.6.30
Operating system ubuntu 14.04

Using composer, recurrent problem in the component update

Hi mans.

In my workspace, in run composer update, every cases, it fail in the twing update version.

This problem is 'uncommited changes'.

I dont manual change files in the folder vendors, the composer is controller for the vendor folder.

Its is know? recurruent issue (i dont track it)....

Twig_Node->getLine deprecated, move to getTemplateLine

What steps will reproduce the problem?

Any rendering produces this error
It is related to an error notice with deprecated function
vendor/twig/twig/lib/Twig/Node.php:131 in Twig_Node->getLine

What's expected?

As per instruction in the warning message :
The Twig_Node::getLine method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateLine() instead.

Additional info

Q A
Yii vesion 2
PHP version 7
Operating system Ubuntu

Path aliases

Allow register path alias and namespace in configuration

Problem with Include helper

Hi, dear Yii2 developers!

I am facing a weird issue with Yii2, Twig and ArrayHelper.

My model hardware has a method devices that returns an array of Device object

So I have this in my view

               {{ use ('yii/helpers/ArrayHelper') }}  
               {#I also try use ('yii\helpers\ArrayHelper')#}
               {{ dump (ArrayHelper.map(devices, 'id', 'name')) }}

That returns: NULL

The only way I can have this working is defining a global in my Twig section's config file this way:

                'globals' => [
                    'array_helper' => '\yii\helpers\ArrayHelper',
                ],

And this this works!

{{ dump (array_helper.map(devices, 'id', 'name')) }}

Why? What if I don't want to define a global but an "use" in my view?

Q A
Yii vesion 2.07
PHP version 7.04
Operating system Arch

Getting return value from register_asset_bundle

Sometimes it can be handy to get the return value of register_asset_bundle.

I've tried with:

{% set bundle = register_asset_bundle('frontend/themes/theme/assets/ThemeAsset') %}

And then for instance to get the property baseUrl of this AssetBundle, but when I do: {{ bundle.baseUrl }} further down it's just an empty string.

In method registerAssetBundle a simple "return" would be enough. I won't create a pull request for such a small thing :)

Would you be interested in a TwigValidator?

What steps will reproduce the problem?

Users that edit Twig templates in the browser inevitably make mistakes.

What's expected?

The input should be validated.

What do you get instead?

No such validator exists.
I have implemented one.

<?php


namespace collecthor\panel\components;


use Twig\Sandbox\SecurityPolicy;
use yii\base\InvalidConfigException;
use yii\validators\Validator;

class TwigValidator extends Validator
{
    /** @var SecurityPolicy */
    public $policy;
    public $strict = false;
    public $variables = [];

    /**
     * List of variables that must be used in the template.
     * Can also be $key => $message format.
     * @var array
     */
    public $mandatoryVariables = [];

    public function init()
    {
        parent::init();
        if (!isset($this->policy)) {
            throw new InvalidConfigException("Policy is mandatory");
        }
    }


    protected function validateValue($value)
    {
        $errors = [];
        $value = html_entity_decode($value, ENT_QUOTES, 'utf-8');
        $loader = new \Twig_Loader_Array([
            '' => $value
        ]);

        $twig = new \Twig_Environment($loader, [
            'debug' => true,
            'strict_variables' => $this->strict
        ]);
        $twig->addExtension(new \Twig_Extension_Sandbox($this->policy, true));
        try {
            $context = [];
            foreach ($this->variables as $key) {
                $context[$key] = md5(mt_rand());
            }

//            var_dump($context);
//            die();
            $result = $twig->render('', $context);

            foreach($this->mandatoryVariables as $variable => $message) {
                if (is_int($variable)) {
                    $variable = $message;
                    $message = "Could not find value of mandatory variable '{variable}' in rendered template.";
                }

                if (strpos($result, $context[$variable]) === false) {
                    $errors[] = strtr($message, [
                        '{variable}' => $variable
                    ]);
                }
            }
        } catch (\Exception $e) {
            $errors[] = $e->getMessage();
        }

        if (empty($errors)) {
            return;
        }

        return [implode(', ', $errors), []];
    }


}

Let me know if you'd like this as part of this library and I'll make a PR.

Using `this.registerJsFile`

What steps will reproduce the problem?

In PHP templates:

// ok
$this->registerJsFile('/js/init_index.js', ['depends' => 'app\assets\AppAsset']);

In Twig templates:

{{ void(this.registerJsFile('/js/init_index.js', {'depends': 'app/assets/AppAsset'})) }}

What do you get instead?

Twig_Error_Runtime

An exception has been thrown during the rendering of a template ("Class app/assets/AppAsset does not exist").

Additional info

Q A
Yii vesion 2.0.11.2
PHP version 7.0
Operating system Linux

how can I use it with twig?

This issue has originally been reported by @klgd at yiisoft/yii2#9275.
Moved here by @cebe.


<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            'id',
            'name',
            [
               'attribute' => 'type',
               'format' => 'raw',
               'value' => function($model, $value, $index, $dataColumn) use ($types) {
                    return $types[$model->type];
               },
            ],
            ['class' => 'yii\grid\ActionColumn', 
                'template' => '{update} {delete}',
            ],
        ],
    ]); ?>

my controller

public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Config::find(),
        ]);
        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'types' => Config::getConfigValue('config_type_list'),
        ]);
    }

Twig functions are not available

This issue has originally been reported by @vladim1 at yiisoft/yii2#10794.
Moved here by @SilverFire.


I want to use twig functions form_begin and form_end in my project. They have been added 2 years ago by this commit. And they are awailable under yii/extensions/twig repository here. But they are not alailable in the yiisoft/yii2-twig repository here (where packagist points). Can anybody update the information? Or what is the reason I can't use the functions?

Implement form_ methods like in Symfony

Current usage of ActiveForm is really complicated.
It requires combination of {{ use() }}, {% set form %} and |raw.

{{ use('yii/widgets/ActiveForm') }}
{% set form = active_form_begin({
    'id' : 'login-form',
    'options' : {'class' : 'form-horizontal'},
}) %}
    {{ form.field(model, 'username') | raw }}
    {{ form.field(model, 'password').passwordInput() | raw }}

    <div class="form-group">
        <input type="submit" value="Login" class="btn btn-primary" />
    </div>
{{ active_form_end() }}

It can be simplified like Symfony's form_ functions
https://symfony.com/doc/current/reference/forms/twig_reference.html

wrong documentation installation

[
    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
]
 'html' => ['class' => '\yii\helpers\Html']

dont work, but

'html' => '\yii\helpers\Html'

work

Additional info

Q A
Yii vesion 2.0.11
PHP version 7.1

twig cachePath does not work

This issue has originally been reported by @nepster-web at yiisoft/yii2#6603.
Moved here by @cebe.


I use twig and theme.
My config:

        'view' => [
             ....
            'renderers' => [
                'layout' => '@app/themes/basic/layouts/main.twig',
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    'options' => [
                        'cache' => true
                    ]
                    ...

But cache twig files is save in the directory: frontend/web/1,
and сreate an empty folder: frontend/runtime/Twig/cache.

Why is this happening?

How can use anonymous functions in twig?

This issue has originally been reported by @RooTooZ at yiisoft/yii2#8401.
Moved here by @cebe.


for example, I want to change the button setting

echo \yii\grid\GridView::widget([
     'id'=>'loggrid',
    'dataProvider' => $dp,
    'columns' => [
      ....
       [
           'class' => \yii\grid\ActionColumn::className(),
           'buttons'=>[
                  'view'=>function ($url, $model) { # how can use this option in twig???
                        $customurl=Yii::$app->getUrlManager()->createUrl(['log/view','id'=>$model['id']]); 
                        return \yii\helpers\Html::a( '<span class="glyphicon glyphicon-eye-open"></span>', $customurl,
                                                ['title' => Yii::t('yii', 'View'), 'data-pjax' => '0']);
               }
            ],
           'template'=>'{view}  {delete}',
       ]
    ],
]);

Adding custom twig extensions

Hi.

Is it possible to add a custom twig extension? For instance I would like to add a hello extension which would output hello, whatever for {% hello %}whatever{% endhello }%, how can I do this?

Tag a release

What steps will reproduce the problem?

Install stable version, and use url-syntax from docs, like so:

{{ url(['/mycontroller2/myaction2'], {'myparam':123}) }}

What's expected?

A rendered page

What do you get instead?

Twig_Error_Runtime

An exception has been thrown during the rendering of a template ("Array to string conversion").

bildschirmfoto 2017-03-25 um 16 02 42

This commit 37c0e39 fixes this.

Additional info

Q A
Yii version 2.0.11 (Twig 2.0.6)
PHP version 7.1
Operating system Linux (Docker)

url() and path() seem to be broken

    public function path($path, $args = [])
    {
        if ($args !== []) {
            $path = array_merge([$path], $args);
        }
        return Url::to($path);
    }

    public function url($path, $args = [])
    {
        if ($args !== []) {
            $path = array_merge([$path], $args);
        }
        return Url::to($path, true);
    }

Both functions pass paths to Url::to as a strings when no arguments are provided. This results in original paths being returned instead of URLs being created by Url::to.

Enh #43 Break compatibility?

What steps will reproduce the problem?

After upgrade to 2.1.0, the twig globals configuration stopped working as expected

   'globals'=>[
       'html'=>'\yii\helpers\Html'
       ... etc
  ]

What's expected?

it should be work, or throw exception about not-supported syntax

What do you get instead?

all usages of aliases declared in globals silently skipped and do nothing
after change configuration like as

   'globals'=>[
       'html'=>['class'=>'\yii\helpers\Html']
       ... etc
  ]

Everything began to work as before upgrade

Additional info

Q A
Yii vesion 2,0,11
PHP version 7,1,3
Operating system Arch

closed issues like #40 are not released

issue #40 is not in released versions. I am using in my composer.json

"yiisoft/yii2-twig": "~2.0.0"

but issue #40 is always here. That's why i submitted yesterday issue #43.
Maybe i supposed to use this

"yiisoft/yii2-twig": "dev-master"

is it secure dev-master?

HtmlHelperExtension not work

What steps will reproduce the problem?

Add to extensions array in config

'extensions' => [
    \yii\twig\html\HtmlHelperExtension::class,
],

What's expected?

Not empty output for:
{{ html.a('any', 'url, { 'class': '123' }) }}

What do you get instead?

Empty output

Additional info

https://twig.symfony.com/doc/2.x/advanced.html#id1

Worked example:

<?php

namespace app\twig\html;
use yii\twig\html\CssClass_TokenParser;
use yii\twig\html\CssStyle_TokenParser;
use yii\helpers\Html;

class HtmlHelperExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{
    public function getTokenParsers()
    {
        return [
            new CssClass_TokenParser(),
            new CssStyle_TokenParser()
        ];
    }

    public function getGlobals()
    {
        return [
            'html' => new Html(),
        ];
    }
}
Q A
Yii version 2.0.13
Yii Twig version 2.2.0
Twig version 2.4.6
PHP version 7.1.9
Operating system Ubuntu xenial

path() and url() with route without params

Hello.

With using path('/mycontroller/myaction') if url rule 'GET mypath' => 'mycontroller/myaction' was defined expected result is /mypath, but now it equals to /mycontroller/myaction.

But path('/mycontroller/myaction', {'myparam':123}) equals to /mypath?myparam=123

It is important when enableStrictParsing option of urlManager was set.

I think path and url tags must have same syntax as Url::to, eg if first params is an array then it should be parsed as route, if string then as custom path.

see PR

register_asset_bundle

Why this function is not returning a value?

    // yii\twig\Extension.php
    public function registerAssetBundle($context, $bundle)
    {
        $bundle = str_replace('/', '\\', $bundle);
        $this->call($bundle, 'register', [
            isset($context['this']) ? $context['this'] : null,
        ]);
    }

What if i will need to use it in my view? like this

$asset = AppAsset::register($this);
echo $asset->baseUrl

replacement controller view path

Hello!

I'm create widget:

<?php
namespace frontend\widgets;

use yii\base\Widget;

class SomeWidget extends Widget 
{
    public function run() 
    {
        $this->render('some.twig');
    }
}

and used it:

{* /frontend/controllers/SiteController::index() *}

{{ use('frontend/widgets/SomeWidget') }}
{{ SomeWidget_widget({}) }}

{{ include('_experts.twig', {selections: selections}) }}

and receive error:

Unable to find template "_experts.twig" (looked into: /var/www/html/frontend/widgets/views) in "index.twig" at line 446.

PS. sorry for my english (google.translate helped me)

Add Blocks example usage to guide

Like

{{ void(this.beginBlock('block1')) }}
now, block1 is set
{{ void(this.endBlock()) }}

<div></div>

{{ this.blocks['block1'] }}

It will save some time

Including templates for other directory

This is my situation:
I have
/view/twig/index/page-index.twig
And I have
/view/twig/block/widgets/modal.twig
I try to use include in page-index.twig block /block/widgets/modal.twig and have an error:
Looks like you try to load a template outside configured directories
But if I change
$loader = new \Twig_Loader_Filesystem(dirname($file));
to
$loader = new \Twig_Loader_Filesystem([dirname($file),Yii::getAlias("@frontend/views/")]);
in vendor/yiisoft/yii2-twig/ViewRenderer.php:148

everythink starts to work properly. and inlclude 'block/widgets/modal.twig' doesn't cause any errors

No errors when using non-existing variable

What steps will reproduce the problem?

Use non-existing variable in view like {{ sdfsfdsfdsf }}

What's expected?

Twig_Error_Runtime exception with message Variable "sdfsfdsfdsf" does not exist...

What do you get instead?

No errors, exceptions nor warnings, so detecting typo in code is hard.

Additional info

Q A
Yii vesion 2.0.12
PHP version 7.1.7
Operating system Ubuntu 16.04 x64

Speeding up rendering

Current rendering speed results are pretty bad: rendering 20 simple widgets with twig templates takes about 2 seconds, imagine complex pages with hundreds of widgets.

In an attempt to speed things up, I refactored the renderer to:

  • Not include aliases
  • Do Twig_Loader_Filesystem in the init function of the view renderer.

These 2 modifications significantly reduce computing time per render, making rendering 20 or 50 widgets almost equally fast. (for 20 widgets computing time reduced from 2,3 sec to 0,19 for my example).

Significant code changes:
[start of init function]

   $loader = new \Twig_Loader_Filesystem(\Yii::$aliases['@app']);
        $this->twig = new \Twig_Environment($loader, array_merge([
            'cache' => Yii::getAlias($this->cachePath),
            'charset' => Yii::$app->charset,
        ], $this->options));

[render function]

public function render($view, $file, $params)
    {
        $this->twig->addGlobal('this', $view);
        $file = str_replace(\Yii::$aliases['@app'], '',$file);
        $template = $this->twig->render($file, $params);
        return $template;
    }

Component is null

I created component, Yii:$app->service. It works in php

But I use a twig: {{ dump(app.service) }}, and result: null

all my component in the twig returns null. Why is this happening?

Profiling

Use Twig_Profiler_Profile() and translate to yii profiler

Trying to get property of non-object after upgrade from 2.0.4 to 2.0.5

What steps will reproduce the problem?

I am using this widget in our projects: https://github.com/dmstr/yii2-prototype-module/blob/master/src/widgets/TwigWidget.php

What's expected?

No error.

What do you get instead?

PHP Notice – yii\base\ErrorException

Trying to get property of non-object

Error is thrown here: https://github.com/yiisoft/yii2-twig/blame/397e711da9aae8b813778e3504b23d80fb1a86f2/ViewRenderer.php#L169

Looks like my $view is empty, this should be checked here or as an alternative we could pass the whole view to the method and check it in the fallback method.

Additional info

Q A
Yii vesion 2.0.9
PHP version 7.0.8
Operating system Debian (Docker)

Unify globals examples in docs

What steps will reproduce the problem?

Read the docs.

What's expected?

Identical keys for identical classes (same as class name).

'Url' => ['class' => '\yii\helpers\Url'],

What do you get instead?

'Url' => ['class' => '\yii\helpers\Url'],

'url' => ['class' => '\yii\helpers\Url'], // new global

Additional info

Q A
Yii vesion n/a
PHP version n/a
Operating system n/a

The lowercase url() built-in helper function could also be differentiated better if using CamelCase keys. Changing this later in an application is quite some pain, since it is case-sensitive.

Documentation in README.md is wrong

Documentation in README.md is wrong.

It has incorrect configuration example in Usage section.There is no 'globals' option in this example, and without this option 'html' variable does not work in templates (i. e. {{ html.csrfMetaTags }} does not work).

Globals - only static classes and objects?

Related to official documentation. Public property globals allows only static classes and objects. But related to guide:

You can define both Yii helpers and your own variables there:

'globals' => [
    'html' => '\yii\helpers\Html',
    'name' => 'Carsten',
    'GridView' => '\yii\grid\GridView',
],

I tried to use 'name' => 'Carsten' and an exception is occurred (when using {{name}} inside template):
Object of class yii\twig\ViewRendererStaticClassProxy could not be converted to string

So is it possible to determine global string variable?

how to set template files extension ?

I config twig in yii ,but template engine only parse files with 'twig' extension . I want to make files with 'html' extension also can be parsed ? how should I config? thanks.

Twig extension very slow when using alias

This issue has originally been reported by @jonny7 at yiisoft/yii2#13683.
Moved here by @samdark.


What steps will reproduce the problem?

I'm using the following to generate a single PDF.

//Find a layout within all layout sub-directories (only two)
        $layoutName = \Yii::getAlias('@twig') . '/' . $action . '.twig';
        $layoutFilePath = \Yii::$app->getViewPath() . $layoutName;
        if( false == is_file($layoutFilePath))
        {
          $layoutName = \Yii::getAlias('@cotwig') . '/' . $action . '.twig';
          $layoutFilePath = \Yii::$app->getViewPath() . $layoutName;
        }

        // confirm data returned
        if(!empty($data) && is_file($layoutFilePath) ){

          $content = $this->renderPartial($layoutName, [ 'model' => $data ] );
          //return $content;
          // load the pdf
          $doc = new Pdf([
            // set to use core fonts only
            'mode' => Pdf::MODE_UTF8,
            // A4 paper format
            'format' => Pdf::FORMAT_A4,
            // portrait orientation
            'orientation' => Pdf::ORIENT_PORTRAIT,
            // stream to browser inline
            'destination' => Pdf::DEST_BROWSER,
            // your html content input
            'content' => $content,
            //Any CSS file which needs to be loaded to sytle render the html
            //'cssFile' => $cssLayoutFilePath, (can't do it here as NULL or "" will remove default style)
            'marginTop' => 5,
            'marginBottom' => 0,
          ]);

          //Determine if there is an css file needed for rendering template
          $cssLayoutFilePath = $layoutFilePath . ".css";
          if( true == is_file($cssLayoutFilePath) )
          {
            //$doc->cssFile = $cssLayoutFilePath; //Note that this will override the loading of css file  @vendor/kartik-v/yii2-mpdf/assets/bootstrap.min.css
            $doc->cssInline = file_get_contents($cssLayoutFilePath);
          }

          // render Pdf
          return $doc->render();

What is the expected result?

I'm unsure of why is_dir is called so often for a simple alias call. In our profiler work, we accounts that of the 10 second generation time, around 7 seconds was due to calling is_dir()

What do you get instead?

Here is a picture of the profiler output: http://tinypic.com/r/t5svpt/9

Additional info

I'm not on an expert on the inner workings of Yii, but wondering if this is something that can be tamed or a legitimate situation that needs to be reviewed

Q A
Yii version 2.11.2?
PHP version 5.6.28
Operating system Windows 7

Wrong documentation additional-configuration.md - Functions

Guide https://github.com/yiisoft/yii2-twig/blob/master/docs/guide/additional-configuration.md#functions says:

You can define additional functions like the following:

'functions' => [
    ...
    'sum' => function ($a, $b) {
        return $a + $b;
    }
],

But I tried it and got exception:

Incorrect options for "Function" sum.
https://github.com/yiisoft/yii2-twig/blob/master/ViewRenderer.php#L254

I'm doing something wrong or there is an actual typo?
Or case 'is_callable' (or similar) just wasn't implemented?

$ composer info -i | grep 'twig'
twig/twig                           v1.24.0            Twig, the flexible, fast, and secure template language for PHP
yiisoft/yii2-twig                   2.0.4              The Twig integration for the Yii framework

A lean fork

I have forked this repo for research purposes and cleaned up the history quite a bit. All committer and tag information has been preserved.

At the time of writing this repo has 4661 commits (9.66 MiB), my fork — 139 (111.39 KiB). I would recommend doing a master and tags reset here.

page cache,csrf & activeform

Hello!

I add page cache to UserController::actionLogin():

<?php

class UserController extends Controller {
    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\PageCache',
                'only' => ['login'],
                'duration' => 3600,
                'enabled'=>Yii::$app->request->isGet,
            ],
        ];
    }
}
{% set form = active_form_begin() %}
  {{ form.field(model, 'username') | raw }}
  {{ form.field(model, 'password').passwordInput() | raw }}

  <div class="form-group">
    <input type="submit" value="Login" class="btn btn-primary" />
  </div>
{{ active_form_end() }}

An first opening page i have correct csrf-tocken but on secondary openning page csrf-tocken not valid.

Temporary solution - manualy add hidden field with csrf-tocken:

{% set form = active_form_begin() %}
  <input type="hidden" name="{{ this.renderDynamic('return \\Yii::$app->getRequest()->csrfParam;') | raw }}" value="{{ this.renderDynamic('return \\Yii::$app->getRequest()->getCsrfToken();') | raw }}">
  ...
{{ active_form_end() }}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.