Code Monkey home page Code Monkey logo

kirby-twig's Introduction

⚠️ This repo moved here and is now maintained by wearejust.

Twig Plugin for Kirby CMS

  • Adds support for Twig templates to Kirby CMS (3.0+).
  • PHP templates still work, you don’t have to rewrite them if you don’t want to.

What it looks like

Before:

<?php /* site/templates/hello.php */ ?>
<h1><?= $page->title() ?></h1>
<ul>
<?php foreach ($page->children() as $child): ?>
  <li><a href="<?= $child->url() ?>"><?= $child->title() ?></li>
<?php endforeach; ?>
</ul>

After:

{# site/templates/hello.twig #}
<h1>{{ page.title }}</h1>
<ul>
{% for child in page.children() %}
  <li><a href="{{ child.url }}">{{ child.title }}</li>
{% endfor %}
</ul>

Installation

Download

Download and copy this repository to /site/plugins/kirby-twig.

Git submodule

git submodule add https://github.com/amteich/kirby-twig.git site/plugins/kirby-twig

Composer

composer require amteich/kirby-twig

Usage

Page templates

Now that the plugin is installed and active, you can write Twig templates in the site/templates directory. For example, if the text file for your articles is named post.txt, you could have a post.twig template like this:

{% extends 'layout.twig' %}
{% block content %}
  <article>
    <h1>{{ page.title }}</h1>
    {{ page.text.kirbytext | raw }}
  </article>
{% endblock %}

See the {% extends '@templates/layout.twig' %} and {% block content %} parts? They’re a powerful way to manage having a common page layout for many templates, and only changing the core content (and/or other specific parts). Read our Twig templating guide for more information.

Hint: Accessing pagemethods instead of public variables

Twig calls to specific methods, like for instance page.children sometimes return NULL. This can occur, if there is also a public variable which is only initialized after calling the corresponding method.

{{ page.children }} returns NULL, because the public variable is returned. Please call the method instead like this: {{ page.children() }}.

Options

You can find a full list of options in the options documentation.


More documentation

License

MIT

Credits

  • Maintainer: Christian Zehetner
  • Twig library: Fabien Potencier and contributors / License
  • Twig plugin for Kirby 2: Florens Verschelde

kirby-twig's People

Contributors

dependabot[bot] avatar ersoma avatar moritzlost avatar renestalder avatar reynaert1250 avatar seehat 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

Watchers

 avatar  avatar  avatar  avatar

kirby-twig's Issues

Custom namespaces not working in Kirby 3.4.2

Hi, I'm getting an error when using custom namespaces with Kirby 3.4.2.

Twig\Error\LoaderError

Line 1 of /home/ubuntu/sites/project/assets/pages/home.twig

There are no registered paths for namespace "layouts".

In config:

'mgfagency.twig.namespace.layouts' => ROOT_PATH . '/assets/layouts',

Thank you!

Availability of model function in template

So, I browsed through the documentation and quickly tried whether a function define in a Kirby model is available in the Twig templates, but It doesn't seem to be.

Is there any way to use regular Kirby page models with the Twig plugin?

Composer install yields InvalidArgumentException

Trying to install via composer as written in the readme yields following error:

[InvalidArgumentException]                                                                                                                                                                                  
  Could not find a matching version of package amteich/kirby-twig. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability  
   (stable).  

Is it possbile you changed the project path/namespace on GitHub and that the old one was mgfagency/kirby-twig , which is still used in the composer repository?

Register new templates?

(While I have your attention!) Is it possible to register new twig templates in a plugin?
Previously, I has something like

Kirby::plugin('your/plugin', [
    'templates' => [
        'blog' => __DIR__ . '/templates/blog.php'
    ]
]);

But pointing directly to a .twig file doesn't seem to work.
I have a feeling it is possible by returning a new amteich\Twig\Template(...) perhaps?, but can't work it out...

Not compatible with kirby layouts extension

Firstly, thanks for this excellent plugin, it works great!

Except just to note that it seems to be incompatible with the kirby layouts plugin.

Now obviously, you won't need <?php layout() ?> if you now have {% extends 'layout.twig' %} - but this caught me out when I was in the process of converting templates, you will need to uninstall/remove the layouts plugin before adding twig.

Site not available inside of a block template

When accessing the site object within a twig template for a block element, I get the following error.

Error: Twig\Error\RuntimeError, line 2 of @templates/blocks/bloglink.twig

{% set page = site.find(block.linkselect) %}
{% set pagetitle = page.title %}
➡ Variable "site" does not exist.

The value block.linkselect is the page.id. My goal is to retrieve the page object so that I can have access to all page object fields for my markup.

Of course I need there to be a site variable available at this level. Or am I going about it wrong?

Templating doesn't work in production with apache

Hi, thanks for your help in advance.
We have a problem with displaying the twig based templating on a production server that runs Apache with the following error:

Screenshot 2020-02-12 00 30 15

On local the code works fine using Laravel Valet.

We think the problem is related with twig, because when we add a default.php page, the default.php gets rendered properly. It's also strange that this message appears only when we want to access the root / of our website although we specified a custom front page for that 'home' => 'start' in the config file (and therefore kirby should render start.twig and not default.php?).
On the other pages it returns 500 Internal server error.

Can you help us with this?

Our template folder:

Screenshot 2020-02-12 00 38 41

page.children returns NULL

Started a new project and wanted to use Twig. I have a dead simple template and page.children returns NULL.

Using Kirby 3.1.4.

{% extends "@templates/base.twig" %}

{% block main %}

    <article>

        <h1>{{ page.title.html }}</h1>
        {{ dump( page.children ) }}

        {% for section in page.children %}
            <section>
                {{ section.title.html }}
            </section>
        {% endfor %}

    </article>

{% endblock %}

{{ dump( page.children ) }} returns NULL and nothing inside the for block is rendered.

Everything works fine in an equivalent PHP template:

<?php snippet('header'); ?>

<article>
    
    <h1><?= $page->title()->html() ?></h1>  
    <?php dump( $page->children() ) ?>

    <?php foreach ( $page->children() as $section ) : ?>

        <section>
            <?= $section->title()->html() ?>
        </section>

    <?php endforeach; ?>
</article>

<?php snippet('footer') ?>

This template successfully outputs all of the page's children's titles. dump() outputs a Pages object.

Any ideas what might be happening?

Error with PHP 8.2

I just updated Kirby (v3.9.0) and PHP (v8.2.1)

I have an error:

Twig\Error\RuntimeError
Line xx of /xxx/layout.twig

An exception has been thrown during the rendering of a template ("mb_convert_encoding(): Handling HTML entities via mbstring is deprecated; use htmlspecialchars, htmlentities, or mb_encode_numericentity/mb_decode_numericentity instead").

I use the latest version of the plugin (v4.2.3)

E-Mail templates with html/text types don't work correctly

I'm trying to create e-mail templates in plain text and HTML using Twig. I have created the following two templates:

  • templates/emails/contact.html.twig
  • templates/emails/contact.text.twig

And I'm sending an email like this:

$kirby->email([
    'from' => '[email protected]',
    'replyTo' => '[email protected]',
    'to' => '[email protected]',
    'template' => 'contact',
    'data' => [
        'foo' => 'bar',
    ],
]);

The e-mail is sent correctly, but the body only includes this error:

Unable to find template "emails/contact.twig" (looked into: /path/to/project/templates, /path/to/project/templates/emails).

Looks like the Template class in the plugin is not handling the $type suffix correctly, but I'm not sure where the error comes from.

Possibility to render block template in block preview

I recently changed my backend and frontend code from kirby-builder towards the official kirby-blocks.

With kirby-builder it was quite easy to get a preview of the page contents by using a 1-line PHP file using the twig-function and defining a required CSS file. Using this, kirby-builder created an iframe showing the current content of the block using the intended template.

If I understood the documentation correctly, with kirby blocks I'd have to rewrite the entire template code as vue-template to get a working preview of the contents.
I wonder, is there any way to achieve a simmilar outcome as with kirby-builder. Of course, live editing wont work if it is not a vue template, but an iframe rendering the actual twig template would be fantastic.

Does anyone know a workaround to render a block preview using the actual twig templates?

open_basedir error in LoaderFilesystem.php

It get an open_basedir error if I'm using kirby-twig on an Plesk Onyx installation with activated open_basedir restrictions. I'm not able to change the default value of {WEBSPACEROOT}{/}{:}{TMP}{/} (role restrictions).

It works fine if I remove these lines in site/plugins/kirby-twig/src/classes/LoaderFilesystem.php:

Line 219:
$templatevariants[] = $shortname . '/' . $templatename . '.twig';

Line 229:
if (is_file($path.'/'.$templatevariant)) {

Line 335:
}

Encoding emails with twig

Is it possible to render encoded email using twig?
Kirby's php code:

<a href="mailto:<?= Str::encode($block->email()) ?>">
    <?= Str::encode($block->email()) ?>
</a>

"need help" - how access form variables in twig

hey,

i am relatively new to kirby and PHP, and have a question about the contact form. how can i access the variables $alert etc. in the template with twig?

I am currently trying to integrate a contact form on the homepage, but I lack any understanding of how to access the data within Twig.

thanks for your help.

PHP 7.4 Support

I think for supporting PHP 7.4 Twig should be updated at least to 2.12.0

Overwriting a default block snippet from inside a plugin does not render the Twig code

I have everything specific to a website in a plugin, including templates, blueprints, controllers. This also works fine with the Twig plugin. I can reference "templates" in my plugin to Twig files instead of PHP.

I noticed, this doesn't seem to work for snippets.

When I try to overwrite the heading block (because my plugin extends the fields via a blueprint), the template content will render as raw output, not rendered by the Twig engine.

Kirby::plugin('website/kirby-plugin', [
'snippets' => [
        'blocks/heading' => __DIR__ . '/snippets/blocks/heading.twig'
    ],
]}

The heading overwrite might look something like this:

{% import '@ui/components/heading/macros.twig' as heading %}

{{ heading.render(block) }}

For all other parts so far, the Twig engine seems to rendered everything properly, just not for those snippets defined in the plugin.

As an example, this works fine:

    'templates' => [
        'default' => __DIR__ . '/templates/default.twig',
        'blog-post' => __DIR__ . '/templates/blog-post.twig',
    ],

It most likely doesn't necessarily have something to do with the fact that this is all defined in a plugin. Entirely possible, this also happens when overwriting default blocks outside a plugin.

Use own plugin function in twig

Hey I coded one plugin but I cannot call it on a twig template

my code looks like:

// index.php from my-plugin

function foo($some_string) {
    return 'hello ' . $some_string;
}
// config.php
// in the past it was something like c::set('twig.function.foo', 'foo');

return [
   ...
    'twig.function.foo' => 'foo',

and my template

//some_template.twig

{{ foo('world') }}

But I got an error as response Unknown "foo" function.

@seehat thanks for the response

Solution

// config.php
return [
   ...
    'mgfagency.twig.function.foo' => 'foo',

Custom namespaces not working

I'm trying to change and use the path to assets. My /site/config/config.php is looking like:

<?php

return [
    ...
    'timezone' => 'Europe/Berlin',
    'mgfagency.twig.namespace.assets' => __DIR__ . '../../assets',
];

Now I try to use it in my template file like:

{{ source('@assets/images/logo.svg') }}

But I'll get the following error:

There are no registered paths for namespace "assets".

Am I missing something?

Thank you!

mgfagency\Twig\Plugin::render fails if called from a route handler

Hallo!
I just found what seams to be a bug. I'm trying to use the twig() helper from a Kirby v3 route handler, then this error is shout

Too few arguments to function mgfagency\Twig\Environment::__construct(), 0 passed in /Users/daniele/projects/v3-kirby/kirby/site/plugins/kirby-twig/src/classes/Environment.php on line 206 and exactly 1 expected

Looks like that the Environment is not properly instantiated. This makes the call to the static method Environment::instance() try to re create the instance (Environment.php:206), and it fails with the error shown.

It also happens that if, before to use twig(), i call the findPageOrDraft method of a site instance, twig() works good (the Environment is properly instantiated);

I hope you can give me some advice to how to handle this scenario. If you need any other information, I will provide them as soon as possible. Thank you in advice.

Support for Twig snippets

Hi. Plugin works great for templates, but it doesn't load snippets with the twig extension.

{{ snippet('subscribe') }}

with the subscribe snippet defined as /snippets/subscribe.twig doesn't do anything.

Would be be possible to extend the plugin to also load in snippets?

I don't know how Kirby handles templates/snippets under the hood, but could it be as simple as adding

'components' => [
        'template' => function (App $kirby, string $name, string $contentType = 'html', string $defaultType = 'html') {
            return new mgfagency\Twig\Template($name, $contentType, $defaultType);
        },
        'snippet' => function (App $kirby, string $name, string $contentType = 'html', string $defaultType = 'html') {
            return new mgfagency\Twig\Snippet($name, $contentType, $defaultType);
        }
    ]

?

PHP Fatal error: require_once(): Failed opening required '[...]/vendor/autoload.php'

Hi there !

I'm trying to use this plugin in a composer install of Kirby.

I ran composer require mgfagency/kirby-twig in the root folder of the project. Plugin has been installed into the site/plugins directory, and vendors in the global vendor directory.

Know I get this error : PHP Fatal error: require_once(): Failed opening required '[...]/vendor/autoload.php'

The require line in the index.php does not seem to be necessary

Global Kirby objects should be added to the environment as globals

The Twig page template receives variables in the $twig->render() call, which means they're available in the template. If I dump the context, I can see the global objects:

{# default.twig #}
{{ dump(_context|keys) }}

This shows kirby, site, pages and page. However, if I include another template without context, those variables aren't available any more:

{# default.twig #}
{{ include('other-template.twig', with_context = false) }}

{# other-template.twig #}
{{ dump(_context|keys) }}

This only dumps an empty array, because no global variables are set.

Passing the global objects manually is tedious, those should be available in every template automatically. This can be accomplished by adding those objects to the Twig environment as globals. At least the four most prominently used objects – $kirby, $site, $pages, $page (if the current route has a page) – should be provided as globals:

$twig->addGlobal('kirby', $kirby);
$twig->addGlobal('site', $site);
$twig->addGlobal('pages', $pages);
$twig->addGlobal('page', $page);

There are probably some other global objects that should be provided as globals. For example: $user, $users, $session and $request.

PHP 8.0 Support

I'm not sure but I think for supporting PHP 8 Twig should be at least at 2.13.0

Class 'Kirby' not found in kirby-twig/config.php

Hey, I tried to install this module on a clean Kirby 3 Beta 6 installation with PHP 7.1

Steps

  1. I installed it with composer, as written in the documentation.
  2. Changed home.php to home.twig an modified the snippets to .twig
  3. Reload of the page

Error:

Fatal error: Uncaught Error: Class 'Kirby' not found in /Users/.../Sites/.../vendor/mgfagency/kirby-twig/config.php on line 5

Have I missed something? #

The documentation for the autoescape option is incorrect

The options documentation includes this example:

// Disable autoescaping or specify autoescaping type
// http://twig.sensiolabs.org/doc/api.html#environment-options
'amteich.twig.autoescape' => true

But setting the option to true causes an error:

call_user_func(): Argument #1 ($callback) must be a valid callback, no array or string given

That's because the option is passed directly as the autoescape option to the Twig environment:

'autoescape' => option('amteich.twig.autoescape', 'html'),

But Twig expects either a string with the default escaping strategy or false to disable autoescaping for that parameter, passing true is not supported.

To fix this, the plugin could check if the option is true and convert it to html, which would be my preferred solution:

$autoescape = option('amteich.twig.autoescape', 'html');
if (true === $autoescape) {
    $autoescape = 'html';
}

If this is not in line with the plugin's intended usage, the documentation at least shouldn't show an invalid option:

// either
'amteich.twig.autoescape' => false

// or
'amteich.twig.autoescape' => 'html'

Is it possible to include snippets of a php library in a twig file?

Hey, first of all, high praise for the helpful plugin :)
I tried to implement the kirby podcaster plugin (https://github.com/mauricerenck/kirby-podcaster) in a project. For the most part, it works fine, but errors have occurred when using twigs include statement with a PHP snippet. Even with the creation of a new namespace, a successful implementation was not possible.

Is there a better way to access the PHP snippets via Twig? Or is it necessary to re-code this part in the branch?

Error when retrieving vars from included template {% include x with y %}

Hello,

Vars sent to included template seems to not be sent or included :

{% include '@snippets/blocks/text.twig' with { 'foo':'bar'} %}

When I do a {{ dump(foo) }} in @snippets/blocks/text.twig, I have an error :

Twig\Error\RuntimeError
Line 3 of .../site/snippets/blocks/text.twig
Variable "foo" does not exist.

Maybe I do something wrong but it doesen't seems

Thank you

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.