Coder Social home page Coder Social logo

twig-view's Introduction

TwigView plugin for CakePHP

CI Latest Stable Version Total Downloads Code Coverage Software License

This plugin allows you to use the Twig Templating Language for your views.

It provides wrappers for common View opertions and many helpful extensions that expose CakePHP functions and jasny/twig-extensions helpers.

Installation

To install with Composer, use the command below.

composer require cakephp/twig-view

Then, load the Cake/TwigView plugin in your Application bootstrap just like other Cake plugins.

Configuration

TwigView allows you to configure the Twig Environment through View options. You can set these through ViewBuilder in the Controller or set them directly in TwigView.

// In controller
public function initialize(): void
{
    $this->viewBuilder()->setOption('environment', ['cache' => false]);
}

// In your AppView
public function initialize(): void
{
    $this->setConfig('environment', ['cache' => false]);

    // Call parent TwigView initialize
    parent::initialize();
}

Available Options

  • environment

    Twig Environment options.

    Defaults to empty.

  • markdown

    Which markdown engine is used for markdown_to_html filter. Set to default to use DefaultMarkdown or set custom Twig Markdown extension MarkdownInterface instance.

    If using default, require one of: - erusev/parsedown - league/commonmark - michelf/php-markdown

    Defaults to disabled.

AppView Setup

To start using Twig templates in your application, simply extend TwigView in your AppView. In general, it is safe to add your application's setup in AppView::initialize().

namespace App\View;

use Cake\TwigView\View\TwigView;

class AppView extends TwigView
{
    public function initialize(): void
    {
        parent::initialize();

        // Add application-specific extensions
    }
}

Customization

You can override several parts of TwigView initialization to create a custom Twig setup.

  • File Extensions

    You can specify the file extensions used to search for templates by overriding the $extensions property.

    class AppView extends TwigView
    {
        protected $extensions = [
            '.custom',
        ];
    }
  • Twig Loader

    You can override the template loader used by Twig.

    protected function createLoader(): \Twig\Loader\LoaderInterface
    {
        // Return a custom Twig template loader
    }
  • Twig Extensions

    You can override the Twig Extensions loading. If you want to use the built-in View wrappers, make sure you load Cake\TwigView\Twig\Extensions\ViewExtension.

    protected function initializeExtensions(): void
    {
        // Load only specific extensions
    }
  • Twig Profiler

    You can override the Twig profiler used when DebugKit is loaded.

        protected function initializeProfiler(): void
        {
            parent::initializeProfiler();
            // Add custom profiler logging using $this->getProfile()
        }

Templates

You can create views using Twig templates much like you can with standard CakePHP templates.

Templates are loaded the same way wherever they are used and follow the View path conventions.

{% extends 'Common/base' %}
{{ include('Common/helper') }}
  • Template names are always relative to App.path.templates not the current file.
  • File extensions are automatically generated. Defaults to '.twig'.
  • Templates can be loaded from plugins the same as View templates.

Layout templates are supported and loaded the same way as View layouts.

templates/layout/default.twig:

<!DOCTYPE html>
<html>
<head>
    <title>
        {{ fetch('title') }}
    </title>

    {{ fetch('meta') }}
    {{ fetch('css') }}
    {{ fetch('script') }}
</head>
<body>
    {{ fetch('content') }}
</body>
</html>

The layout can be set from the template using the layout tag.

{% layout 'Error' %}

Accessing View

You can access the View instance using the _view global.

TwigView provides wrappers for fetch(), cell() and element() rendering. Cell and element templates are always loaded from cell/ and element/ sub-directories the same as View templates.

{{ fetch('content')}}

{{ cell('myCell')}}
{{ element('myElement') }}

TwigView also provides wrappers for any loaded helper using a special naming convention - helper_Name_function().

{{ helper_Text_autoParagraph('some text for a paragarph') }}

All wrapper functions are pre-escaped and do not require using |raw filter. However, keep in mind that Twig keeps the whitespace when using {{ }} to print. Please read the Twig documentation on how to remove the extra white space when needed.

Extension Filters

See jasny/twig-extensions for the filters they provide.

Extension Functions

See jasny/twig-extensions for the functions they provide.

twig-view's People

Contributors

admad avatar arhell avatar batopa avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dereuromark avatar edggk avatar fabian-mcfly avatar havokinspiration avatar imgbotapp avatar inoas avatar jadb avatar joshualuckers avatar julianpollmann avatar lordsimal avatar lorenzo avatar m3nt0r avatar markstory avatar mechtecs avatar othercorey avatar ozee31 avatar peter279k avatar predominant avatar rewish avatar scrutinizer-auto-fixer avatar shama avatar steinkel avatar vonboth avatar wyrihaximus avatar

Stargazers

 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

twig-view's Issues

Link to twig docs broken

The external docs link for Twig points to the old sensiolabs twig.sensiolabs.org domain which is no longer publicly resolvable.
This should be changed to the new twig.symfony.com domain.

Improve helper integration so templates don't need raw

Currently all helper output needs to be passed through the raw filter. For example:

{{ Html.link('View this thig', "https://example.com/")|raw }}

This is not idea as it trains people to use raw which is an unsafe practice. Instead it would be better if we didn't have to use raw. This might require generating twig functions for each helper method or using a runtime extension that works with the compile steps to generate extension methods.

i18n extract from .twig-files

I'm not quiet sure if this belongs here or if it should be part of the cakephp repo.

Currently cakephp's i18n extract-command only looks for and reads files with the php-extension (https://github.com/cakephp/cakephp/blob/8b5d4b65ca63478bb525042eb95071d6749b5c30/src/Command/I18nExtractCommand.php#L839)

This leads to missing translatable strings from .twig-files when using this twig-view-package.

Simply adding the twig-extension in the lookup is not sufficient because the _extractTokens()-method of that command uses php's token_get_all()-function (see https://github.com/cakephp/cakephp/blob/8b5d4b65ca63478bb525042eb95071d6749b5c30/src/Command/I18nExtractCommand.php#L431)

The two main questions I have:

  1. How to parse the twig templates files and look for calls to the i18n functions?
  2. How to add that functionality to the command line?
    Should this package provie a standalone extract command? Would it be possible to extend cakephp's I18nExtractCommand?

Static Twig environment issue

Is there any reason the Twig\Environment is a static property in the TwigView?

This creates an issue where for example we have differently configured environments for an app view and a mailer view. Once the environment for an app view is set up it is then reused in a mailer view even if the environment config is different.

Unknown "getVars" function.

With this in my Twig template:

{% do getVars()|debug %}

I get the following output when baking:

2020-06-10 21:46:47 Error: [Twig\Error\SyntaxError] Unknown "getVars" function. in /srv/app/plugins/ThemeCms/templates/bake/Template/index.twig on line 10
Stack Trace:
- /srv/app/vendor/twig/twig/src/ExpressionParser.php:446
- /srv/app/vendor/twig/twig/src/ExpressionParser.php:235
- /srv/app/vendor/twig/twig/src/ExpressionParser.php:175
- /srv/app/vendor/twig/twig/src/ExpressionParser.php:70
- /srv/app/vendor/twig/twig/src/TokenParser/DoTokenParser.php:25
- /srv/app/vendor/twig/twig/src/Parser.php:182
- /srv/app/vendor/twig/twig/src/Parser.php:95
- /srv/app/vendor/twig/twig/src/Environment.php:479
- /srv/app/vendor/twig/twig/src/Environment.php:507
- /srv/app/vendor/twig/twig/src/Environment.php:348
- /srv/app/vendor/twig/twig/src/Environment.php:309
- /srv/app/vendor/cakephp/twig-view/src/View/TwigView.php:297
- /srv/app/vendor/cakephp/cakephp/src/View/View.php:1121
- /srv/app/vendor/cakephp/bake/src/View/BakeView.php:100
- /srv/app/vendor/cakephp/bake/src/Utility/TemplateRenderer.php:101
- /srv/app/vendor/cakephp/bake/src/Command/TemplateCommand.php:388
- /srv/app/vendor/cakephp/bake/src/Command/TemplateCommand.php:343
- /srv/app/vendor/cakephp/bake/src/Command/TemplateCommand.php:127
- /srv/app/vendor/cakephp/cakephp/src/Console/BaseCommand.php:175
- /srv/app/vendor/cakephp/cakephp/src/Console/CommandRunner.php:336
- /srv/app/vendor/cakephp/cakephp/src/Console/CommandRunner.php:171
- /srv/app/bin/cake.php:12

Versions:

  • cakephp/bake 2.1.1
  • cakephp/cakephp 4.0.8
  • cakephp/twig-view 1.0.2

Baking is working fine otherwise.

Use function notation for elements and cells

Instead of:

{% element 'Plugin.Element' {
    dataName: 'dataValue'
} {
    optionName: 'optionValue'
} %}

Use something like:

{{ element('Plugin.Element', data=[], options=[]) }}

With this you can assign the output to variables or echo directly in a cleaner way. This also lets you clarify data and options using named parameters.

Support twig loading templates from plugins and without extensions

Currently, you must use the full filename for templates that twig loads from extends and include().

{{ include('my_template.twig') }}

We want to support loading templates the same as View and with better backwards compatible support for wyrihaximus/TwigView.

{% extends 'Plugin.name' %}

{{ include('my_template') }}

This should use the same $extensions property that TwigView uses to load View templates.

5.x Implement Tags for CakePHP View Template Block Builder

// public function setTheme($theme); // Does it make sense to set the theme from a twig template?
public function setLayout($name);
public function start($name);
public function prepend($name, $value);
public function append($name, $value);
public function assign($name, $value);
public function reset($name);
public function end();
public function extend($name);

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.