Sunday 18 August 2019

php - How to create an extension using Twig

I am running apache and php on Ubuntu 17.04
I am using twig. I installed Twig like this.



cd /var/www/html/my-new-website
composer install twig/twig
composer require twig/twig



At this point the way I have been using Twig is: first I create a php file and do some stuff, create an array and render the template with the array data. Next I have separated sections of my page and put them in templates.



here is an example index.php that creates an array of directories then renders it with the files.html.twig located in the templates directory.



require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',

));

$dir = "path/to/dir";
$exclude = array( ".","..",".*","index.php" );
$files = array_diff(scandir($dir), $exclude);

/*
echo ''; print_r($files);
*/


$template = $twig->loadTemplate('files.html.twig');
echo $template->render(['files' => $files]);
?>


here is the files.html.twig, it extends "base.html.twig"



{% extends "base.html.twig" %}

{% block title %}

My Directory Listing
{% endblock %}

{% block content %}
{% for file in files %}
  • {{ file }}

  • {% endfor %}
    {% endblock %}



    and the base.html.twig contains main wrapper with navbar and footer. This all works as expected.



    Right now I have the navbar in my base.html.twig, it is just html where I have to edit the items.



    I have made a php function to get the navbar array that works in a template(navbar.html.twig), but the problem is I have to put or include this php function in each page I create. I want my navbar.html.twig template to get the array from the php funtion directly.



    I believe I need to create a twig extension(php function) and register it. I have read the docs on this(all seem to be for a full symfony install, I am using twig only).



    I think this article is on the right path but did not give me the information I needed to understand Call PHP function from Twig template




    I do not get




    1. where to put my php function? Can I just create a folder called extensions and put a navbar-list-funtion.php file in there?

    2. where to register the function so it can be called from a template? some documentation say to register in the app/config/services.yml (I do not have this file or directory)

    3. after I put the php function in a recognized place, then register it properly,... how will I call the returned array in the template navbar.html.twig?

    No comments:

    Post a Comment

    php - file_get_contents shows unexpected output while reading a file

    I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...