Code Monkey home page Code Monkey logo

kirby-twig's Introduction

Twig Plugin for Kirby CMS

  • Adds support for Twig templates to Kirby CMS 2.x.
  • 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

Standard installation

  1. Download the latest release.
  2. Unzip, rename the kirby-twig-main folder to just twig and put it in your project’s site/plugins folder.

You should end up with a folder structure like this:

site
 └─ plugins
     └─ twig
         ├─ lib
         ├─ src
         └─ twig.php

Using Composer

Require fvsch/kirby-twig in your Composer dependencies:

composer require fvsch/kirby-twig:^3.0

Then, make sure your Kirby installation is autoloading Composer dependencies on both frontend and panel. For this, the safest way is to create your own custom plugin.

site
 └─ plugins
     └─ composer
         └─ composer.php
<?php
// site/plugins/composer/composer.php

// Composer autoload
require_once kirby()->roots()->index() . '/vendor/autoload.php';

Finally, register the plugin by adding this line to your newly created site/plugins/composer/composer.php, after having required the autoloader.

// Register the Twig plugin's template component
Kirby\Twig\Plugin::register();

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 '@templates/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.

Rendering a template in PHP: the twig helper

This plugin also enables a twig PHP function for rendering template files and strings, like this:

<?php

// Render a simple template from the site/snippets directory
echo twig('@snippets/header.twig');

// Same, but passing some additionnal variables
echo twig('@snippets/header.twig', ['sticky'=>false]);

// Render a string
echo twig('Hello {{ who }}', ['who'=>'World!']);

If you work with Twig templates for pages, you might not need the twig() helper at all. But it can be useful when working with the Modules and Patterns plugins.

More documentation

Recommended reads:

Other topics:

Credits

kirby-twig's People

Contributors

knuch 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

Watchers

 avatar  avatar  avatar

kirby-twig's Issues

Support for resize or thumb

Whats your approach when it comes to resizing images? Kirbys resize and thumb functions don't seem to work?

Improve installation guide using composer

Please improve the guide to how to install kirby-twig using composer the current 2 steps are not good enough, does the user require to include /vendor/autoload.php somewhere, are any other steps/dependencies necessary?

Somehow allow adding safe functions

Currently there is no way to add a helper function that is_safe. Maybe the internally used * prefix can be used or you can consider exposing the Twig Environment. Haven't thought this through yet though.

cookie::get() won't work

Hi there!

Is it possible to geht kirbys cookie::get to work with twig? Or is there any workarround?

Missing variables error in header.php

Hi,
I just installed this plugin and I'm getting some errors:

( ! ) Notice: Undefined variable: site in /path/to/site/snippets/header.php on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0002  242824  {main}( )   ../index.php:0
2   0.0144  973712  Kirby->launch( )    ../index.php:16
3   0.0528  3328152 Kirby\Component\Response->make( )   ../kirby.php:686
4   0.0528  3328616 Kirby->render( )    ../response.php:29
5   0.0554  3368936 Kirby->template( )  ../kirby.php:607
6   0.0554  3369120 Kirby\Plugin\Twig\TwigTemplate->render( )   ../kirby.php:619
7   0.0568  3401176 Tpl::load( )    ../TwigTemplate.php:74
8   0.0569  3422048 require( '/path/to/site/templates/default.php' )    ../tpl.php:22
9   0.0569  3422160 snippet( )  ../default.php:1
10  0.0570  3431712 Kirby\Component\Snippet->render( )  ../helpers.php:12
11  0.0579  3442984 Tpl::load( )    ../snippet.php:38
12  0.0583  3467200 require( '/path/to/site/snippets/header.php' )  ../tpl.php:22

And:

( ! ) Fatal error: Call to a member function title() on null in /path/to/site/snippets/header.php on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0002  242824  {main}( )   ../index.php:0
2   0.0144  973712  Kirby->launch( )    ../index.php:16
3   0.0528  3328152 Kirby\Component\Response->make( )   ../kirby.php:686
4   0.0528  3328616 Kirby->render( )    ../response.php:29
5   0.0554  3368936 Kirby->template( )  ../kirby.php:607
6   0.0554  3369120 Kirby\Plugin\Twig\TwigTemplate->render( )   ../kirby.php:619
7   0.0568  3401176 Tpl::load( )    ../TwigTemplate.php:74
8   0.0569  3422048 require( '/path/to/site/templates/default.php' )    ../tpl.php:22
9   0.0569  3422160 snippet( )  ../default.php:1
10  0.0570  3431712 Kirby\Component\Snippet->render( )  ../helpers.php:12
11  0.0579  3442984 Tpl::load( )    ../snippet.php:38
12  0.0583  3467200 require( '/path/to/site/snippets/header.php' )  ../tpl.php:22

The whole error output is dumped right after opening the <title> tag. After the error output nothing else is rendered.

I'm running Kirby 2.3.2 and manually installed the plugin.

Add a file method

Add a file method to return a twig template path.

This would fix $page->hasTemplate().

how to use twig 2.x

using composer to install fvsch/kirby-twig still does not allow one to install twig ^2.4.4. any ideas how to upgrade?

Can't register namespaces, functions & filters in plugins

It seems as if using $kirby->options has the downside that anything you set outside/after config.php is being ignored. That is kind of sad because unless I got something really wrong you can't add anything from plugins now in contrast to what the docs say.

I'm pretty new to kirby, but I think that one would need to use c::$data and c::get() to make this work.

Let me know if you need any more infos on this.

Add support for plugins

In my plugin I register a template:

$kirby->set('template', 'commands', __DIR__ . '/templates/commands.php');

When I change this to use a twig extension ...

$kirby->set('template', 'commands', __DIR__ . '/templates/commands.twig');

... it doesn't work anymore.

Do I have to create an empty commands.php template and just add the commands.twig or can I get rid of the commands.php file somehow?

Documentation: twig.function.* option

Document the new way to expose a function in the templating environment:

c::set('twig.function.myFunction', 'myFunctionsFullName');
c::set('twig.function.myFunction', function(){ /* return something */ });

And similarly for filters.

The old way, c::set('twig.env.functions', ['myFunctionsFullName']);, still works.

This feature enables plugins to register Twig functions and namespaces:

c::set([
  'twig.function.doSomething' => 'MyPlugin::doSomething',
  'twig.namespace.myplugin'   => __DIR__ . '/templates'
]);

Write controller for included twig-module and not for page/template

I have a setup where I create twig pages which mostly consist of included twig modules. When I now want to write a controller file, I have to name this similar as the page name. I would prefer to name it after the module name, so that I can I just embed the module on whatever page and it loads the content automatically, without me having to add a controller for each page which includes the module (with the same code!).

So is there a way I can tell a module where to get it's controller from? Or how would you approach this challenge?
(Maybe this is even a kirby-related question, I don't really know...)

Thanks for your help

Cheers

Unable to find templates with WAMP or XAMPP on windows

Everything is working well with mamp and on production server. But I got an error with XAMPP or WAMP :
Twig_Error_Loader
Unable to find template "C:/xampp/htdocs/site/templates/home.twig" (looked into: C:\xampp\htdocs\site\templates).

it seems that there is something with FileSystem.php line 212

foreach ($this->paths[$namespace] as $path) {
         if (!$this->isAbsolutePath($path)) {
                $path = $this->rootPath.'/'.$path;
            }
           if (is_file($path.'/'.$shortname)) {
                if (false !== $realpath = realpath($path.'/'.$shortname)) {
                    return $this->cache[$name] = $realpath;
                }
                return $this->cache[$name] = $path.'/'.$shortname;
            }
        }

I thought it was because of slashes and anti-slashes but, if I change :

is_file($path.'/'.$shortname)

with :

is_file($shortname)

and

return $this->cache[$name] = $path.'/'.$shortname;

with :

return $this->cache[$name] = $shortname;

It finds the home.twig but than can't find snippets or all included twig templates in my home.twig file.

Any suggestions would be appreciate ! Thanks

Layouting

Hi there, nice plugin.

I have two questions:

  1. how do i use the snippet helper with twig?
  2. is it possible to use twig layouts (blocks) with this plugin?

BR
Marc

How to output config values, getting an error?

Hi guys,

When using {{ l__get(configName, defaultValue) }} to get any config values that I have in site/languages/ gives me an error of Unknown "l__get" function. Any reason why?

Your help will be much appreciated! Thanks in advance :)

The custom twig error page is not working.

It seams that the path when loading the error template isn't correct. Shouldn't it be like this:

$html = Tpl::load(dirname(__DIR__) . DS . 'templates' . DS . 'twigerror.php', [
    'title' => $title,
    'message' => $message,
    'file' => $file,
    'code' => $code
]);
return new Response($html, 'html', 500);

How to get file URL

When using page.field.toFile.url it returns (unknown) while page.field.toFile returns the filename and dump(page.field.toFile) returns an object. How do I get the URL?

Complete install with Composer

For projects that are set up with Composer, could we install this plugin that way?

Dual install method: check if Twig_Environment class exists (it should if we installed the plugin through Composer), try to require plugin/twig/vendor/autoload.php otherwise.

Kirby 3 Version

Are you already working on an update for Kirby 3? - If not, I could help and start working on a pull request.

Does this even work on Kirby 3?

Been trying to get this to work on my Kirby3 test install to no avail... does this plugin even work or am I missing something?

How to load twig templates with Kirby function tpl::load

Hi,

is it possible to load or pass twig templates with the tpl::load() function?

array(
	'pattern' => array('(:any)/(:any)/details/(:any)'),
	'action'  => function($i18n, $section, $details) {
		$items_section = site()->visit($section, $i18n)->children()->visible();
		$items_topic = $items_section->children()->findBy('slug', $details);

		if ( isset($items_topic) && !empty($items_topic) ){
			tpl::$data = array_merge(tpl::$data, array(
				'kirby' => kirby(),
				'site' => site(),
				'pages' => pages(),
				'page' => $items_topic
			), $items_topic->templateData());

			echo tpl::load( kirby()->roots()->templates() . DS . 'sometemplate.twig');
		}
	},
	'method' => 'GET'
)

Of course this doesn't works because the file will not be rendered! Maybe someone can help me please or can show me another solution?

twig plugin interferring although not registered

I was trying both, twig and blade, first I downloaded twig and registered it as recommended. Then I switched over to blade because the page will maybe made in future time with laravel for some reasons. So I deregistered (commented out) twig in config file. But twig nevertheless caused Problems with blade. I had to remove the twig plugin for blade to work.

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.