Giter Site home page Giter Site logo

codeigniter-ss-twig's Introduction

CodeIgniter Simple and Secure Twig

Latest Stable Version Total Downloads Latest Unstable Version License

This package provides simple Twig integration for CodeIgniter 4.x.

If you use CodeIgniter 3, check master branch. But Upgrading to CodeIgniter 4 is strongly recommended.

Requirements

  • PHP 7.4 or later
  • CodeIgniter 4.2.11 or later
  • Twig 3.4.3 or later

Installation

With Composer

$ cd /path/to/codeigniter/
$ composer require kenjis/codeigniter-ss-twig

Usage

Loading Twig Library

$this->twig = new \Kenjis\CI4Twig\Twig();

You can override the default configuration:

$config = [
    'paths' => ['/path/to/twig/templates', VIEWPATH],
    'cache' => '/path/to/twig/cache',
];
$this->twig = new \Kenjis\CI4Twig\Twig($config);

Rendering Templates

Render Twig template and output to browser:

$this->twig->display('welcome', $data);

The above code renders Views/welcome.twig.

Render Twig template:

$output = $this->twig->render('welcome', $data);

The above code renders Views/welcome.twig.

Adding a Global Variable

$this->twig->addGlobal('sitename', 'My Awesome Site');

Getting Twig\Environment Instance

$twig = $this->twig->getTwig();

Supported CodeIgniter Helpers

  • base_url()
  • site_url()
  • anchor()
  • form_open()
  • form_close()
  • form_error()
  • form_hidden()
  • set_value()
  • csrf_field()
  • validation_list_errors()

Some helpers are added the functionality of auto-escaping for security.

Warning validation_list_errors() shows Validation Errors by Services::validation()->listErrors(), and if you use user input for Validation Error messages, attackers may do XSS. In such a case, validate user input and escape it by yourself.

Adding Your Functions & Filters

You can add your functions and filters with configuration:

$config = [
    'functions'      => ['my_helper'],
    'functions_safe' => ['my_safe_helper'],
    'filters'        => ['my_filter'],
];
$this->twig = new \Kenjis\CI4Twig\Twig($config);

If your function explicitly outputs HTML code, you want the raw output to be printed. In such a case, use functions_safe, and you have to make sure the output of the function is XSS free.

References

Documentation

Samples

How to Run Tests

$ cd codeigniter-ss-twig
$ composer install
$ vendor/bin/phpunit

Related Projects for CodeIgniter 4.x

Libraries

Tutorials

Building Development Environment

codeigniter-ss-twig's People

Contributors

atlza avatar datamweb avatar kenjis avatar kimtree avatar miqueiaspenha avatar ytetsuro 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

codeigniter-ss-twig's Issues

improvement

Can you add configuration for twig in codeigniter.

Using with Twig 2.x

In Readme, it says we can check out with Twig 2.x but when I do it, it gives me the following error:

Fatal error: Class 'Twig_Loader_Filesystem' not found in 
/.../Code/myproject/application/libraries/Twig.php on line 117

Do we need to something else for Twig 2.x. By the way I am using Composer to install Twig and other packages.

Session flashdata

How can i do this, with this twig template engine please ?

  <?php if($this->session->flashdata('category_created')): ?>
    <?php echo '<p class="alert alert-success">'.$this->session->flashdata('category_created').'</p>'; ?>
  <?php endif; ?>

Truncate filter does not work

Using {{post.content|truncate(100)}} or {{post.content|raw|truncate(100)}} (with Twig 1.44.1) does not work.
The application throws an Unknown "truncate" filter error message.

Delayed updates on views regarding changes made to variables on controllers.

Hello. I've installed codeigniter-ss-twig, under Bitnami LAMP Stack, following the instructions using composer and also manually, and in both cases when changes are made to variables on controllers, there's a delay (after some page refreshes) to get them updated when the view is rendered on the browser. This issue is only regarding variables. Changes made to static content on the view gets updated immediately when the page refreshes. I've tried even setting up the cache to false on the libraries/Twig class.

It was a default Bitnami Lamp Stack configuration issue. I edited the php.ini file and changed option opcache.enable from 1 to 0. I couldn't imagine Bitnami LAMP Stack wasn't properly setup for development environments.

Great work with the codeigniter-ss-twig, Kenjis.

Override another twig configs?

Twig.php

__construct()

// default config
$this->config = [
    'paths' => [VIEWPATH],
    'cache' => APPPATH . 'cache/twig',
];

createTwig()

$twig = new \Twig_Environment($this->loader, [
    'cache'       => $this->config['cache'],
    'debug'       => $debug,
    'autoescape'  => TRUE,
]);

Twig_Environment($loader, $config_array);

Can extend $config_array another twig environment options without editing Twig.php ?
I need to extend config like 'auto_reload'.

http://twig.sensiolabs.org/doc/api.html#environment-options

form helper

Hi, Kenji!

Thanks for this project. I am able to seamlessly, integrate twig into CI. 😄

Just a quick question, how can I use form helper functions? like form_input, form_select, form_password.

Thanks!

Unable to use form helpers

First of all i want to thank you for your work. I have a problem with helper function, i tried to use site_url function like {{ site_url }} and its working fine but other functions like form_error and set_value are not working.

  • Thanks

translation with twig and ci

Hello kenjis

I recently installed your twig module on a project code igniter 3, it work very properly

However, I must now translate on this project.

is it possible or not?

I can not seem to recover my translation in my views

thank you in advance

Using helpers

This is probably a pretty simplistic question, but in looking around I haven't found an answer. How would I use the CI helpers included in this library. For instance how would I use base_url? I've tried {{base_url}} and {{base_url()}} neither of which worked.

Just looking for a little guidance here. Thanks.

Fatal error: Class 'Twig_Loader_Filesystem' not found in

Hi,

Just installed this via composer then ran the install.php file.

I get the following error

Fatal error: Class 'Twig_Loader_Filesystem' not found in /var/www/html/procurement/application/libraries/Twig.php on line 63

I am running codeigniter 3.03
Apache2
PHP 5.5.9
Linux Mint 17

Any ideas what I have done wrong.

[Question] Only one display for function?

Hi!
I want to display Header, content and footer. When I use:
$this->twig->display('Header');
Everythink works perfectly, but when i write below
$this->twig->display('Footer');
i can see only footer etc.

I can see only last display in function.

Twig global variable doesnt work

Hi im adding global variable in my login controller.

  if($user){
            $user_credentials["user_session"] = [
                "user_id" => $user->user_id,
                "fullName" => $user->name. " ".$user->surname,
                "email" => $user->email,
                "logged_in" => true
            ];
            $this->session->set_userdata($user_credentials);
            $this->twig->addGlobal('user_session',$user_credentials["user_session"]);
            redirect('dashboard');
        }

In my dashboard.twig file im calling {{ user_session.fullName}} but it doesnt work.
BUT
If i use addGlobal method in my dashboard i can see the fullName variable. In this case it doesnt work for another controllers, works for only dashboard. But i need to use it in every controller.

Layouts & templates?

I'm unfamiliar with CodeIgniter (just learning) but I see some stuff elsewhere on the web referencing templates and layouts in CI 2, and specifically with the older twiggy (http://stackoverflow.com/questions/19482485/using-twig-in-codeigniter-project). Does your integration of twig support this sort of template/layout configuration?

Can I configure a default layout that will always be rendered around the view content whenever I call:
$this->twig->display('[view]',$data);

Using official filters from Twig

How to use the official filters from Twig?
I'm trying to use markdown_to_html.

  • It is installed using Composer (composer require twig/markdown-extra)

  • I tried adding it to the configuration $config = [ 'filters' => ['markdown_to_html'] ]

  • I also tried to add:
    use Twig\Extra\Markdown\DefaultMarkdown; use Twig\Extra\Markdown\MarkdownRuntime; use Twig\RuntimeLoader\RuntimeLoaderInterface;

Is this generally supported by codeigniter-ss-twig?

Unable to create the cache directory

Hi, I want to display prepared twig template, but app shows me a message that unable to create cache directory.

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to create the cache directory (/usr/home/pfilipek/homewww/ci3-doctrine/application/cache/twig/42).

Filename: /usr/home/pfilipek/homewww/ci3-doctrine/vendor/twig/twig/lib/Twig/Cache/Filesystem.php

Line Number: 57

Backtrace:

File: /usr/home/pfilipek/homewww/ci3-doctrine/vendor/twig/twig/lib/Twig/Environment.php
Line: 452
Function: write

File: /usr/home/pfilipek/homewww/ci3-doctrine/vendor/twig/twig/lib/Twig/Environment.php
Line: 362
Function: loadTemplate

File: /usr/home/pfilipek/homewww/ci3-doctrine/application/libraries/Twig.php
Line: 174
Function: render

File: /usr/home/pfilipek/homewww/ci3-doctrine/application/libraries/Twig.php
Line: 156
Function: render

File: /usr/home/pfilipek/homewww/ci3-doctrine/application/controllers/Welcome.php
Line: 55
Function: display

File: /usr/home/pfilipek/homewww/ci3-doctrine/index.php
Line: 315
Function: require_once

cache directory exists and I setted permissions but it still doesn't work.

custom directory template

Hi, I use HMVC and create a module to create an interface on the client side, I want to put the master template in my module, but there is an error like this:

An uncaught Exception was encountered
Type: Twig_Error_Loader

Message: Unable to find template "welcome.twig" (looked into: /home/wisnu/web/gtln/application/views).

Filename: /home/wisnu/web/gtln/vendor/twig/twig/lib/Twig/Loader/Filesystem.php

Line Number: 232

Backtrace:

File: /home/wisnu/web/gtln/vendor/twig/twig/lib/Twig/Loader/Filesystem.php
Line: 150
Function: findTemplate

File: /home/wisnu/web/gtln/vendor/twig/twig/lib/Twig/Environment.php
Line: 329
Function: getCacheKey

File: /home/wisnu/web/gtln/vendor/twig/twig/lib/Twig/Environment.php
Line: 419
Function: getTemplateClass

File: /home/wisnu/web/gtln/vendor/twig/twig/lib/Twig/Environment.php
Line: 362
Function: loadTemplate

File: /home/wisnu/web/gtln/application/libraries/Twig.php
Line: 155
Function: render

File: /home/wisnu/web/gtln/application/libraries/Twig.php
Line: 137
Function: render

File: /home/wisnu/web/gtln/application/modules/front/controllers/Welcome.php
Line: 18
Function: display

File: /home/wisnu/web/gtln/application/libraries/REST_Controller.php
Line: 793
Function: index_get

File: /home/wisnu/web/gtln/index.php
Line: 315
Function: require_once

when I fill out your library following its configuration:
in the / module / front / controller directory

class Welcome extends REST_Controller {
	public function __construct()
	{
		parent::__construct();
		$config = [
			'paths' => [APPPATH.'modules/front/views/template'],
			'cache' => APPPATH.'cache/twig',
		];
		$this->load->library('twig',$config);
	}

	public function index_get()
	{
		$this->twig->display('welcome', ['message'=>'hello']);
	}
}

how to configure my template to be on the module I created? thank you,

How to use session flashdata function

Hi Kenji,

How can I use the $this->session->flashdata() in my view?

If I set the flashdata in my controller like this:

$this->session->set_flashdata('success', 'Test message');
redirect('/', 'refresh');

How can I call it on my view?

Thanks!

how to setting twig with hmvc in codeigniter, please?

An uncaught Exception was encountered
Type: Twig_Error_Loader

Message: Unable to find template "test.twig" (looked into: E:\xampp\htdocs\ci_blog2\application\views).

Filename: E:\xampp\htdocs\ci_blog2\vendor\twig\twig\lib\Twig\Loader\Filesystem.php

Line Number: 232

Installer copy() assumes wrongly

This is an excerpt from the installer:

class Installer
{
    public static function install()
    {
        self::copy('vendor/kenjis/codeigniter-ss-twig/libraries/Twig.php', 'application/libraries/Twig.php');
    }
}

There has to be a way to pass the path to the install method so that it adjusts depending on the user set-up.

Below is an example of my usual set-up:
-- [CodeIgniter Base]
    -- .app/
      -- v1/
        -- (application files...)
      -- vendor/
        -- (composer vendor libraries...)
    -- .sys/
      -- (system files...)
    -- web/
      -- (public path; contains index.php)

Trying to use ckeditor and ckFinder with twig and CI

Ok I'm a retard.

Add the folders and give the class to the textarea.

I'm trying to use ckEditor, ckFinder and twig & CI.

For this I'm trying to create a function that calls the editor method on the library ckEditor, but I can't make it work. I'm doing the following:

#twig_helper.php

function editor($name, $id, $value = "", $config = array(), $events = array()){
     echo $this->ckeditor->editor($name, $id, $value = "", $config = array(), $events = array()); 
}

controller.php

$this->load->helper('twig');
$config = [
  functions' => ['editor']
];
$this->load->library('twig', $config);
$this->data['content'] = $this->twig->render('view.php', array('imgurl' => $this->data['imgurl']));
$this->twig->display('index.php', $this->data); 

view.php
{% editor("textarea name","default textarea value") %}

Receiving the following error:
Type: Twig_Error_Syntax
Message: Unknown "editor" tag.

I don't know if it exists a simpler way to do this, or if i'm making some mistakes on my code. I'll accept any advice.

I'm using ckEditor and ckFinder without twig, following the tutorial below, without problems.
http://www.webpreparations.com/how-to-integrate-ckeditor-in-codeigniter-using-bootstrap/

But obviously i can't call the php method ckeditor->editor("textarea name","default textarea value"); ?> on the twig view.

Regards and thank you for your help.

Unable to Install

I installed the twig package and when i am installing kenjis/codeigniter-ss-twig package i got "Your requirements could not be resolved to an installable set of package" message. Please help

ERROR: Class 'CI_Twig' not found

Hi @kenjis,

I installed codeigniter-ss-twig and work very well, but for some reason I get this error:

Fatal error: Class 'CI_Twig' not found in /path/to/codeigniter/system/core/Common.php on line 196

Here it's a screenshot of the problem:

errortwig

it's related to the librarie? Any help?

Class 'Kenjis\CI4Twig\Twig' not found in CI4

Hi Kenjis, I've used this fantastic project before in a CI3 project.

However i'm trying to use it in a new CI4 project and i'm getting the following error:
"Class 'Kenjis\CI4Twig\Twig' not found"

I've installed via Composer and everything is sitting in my vendor folder ready to go.

I'm using the following code in my CI4 controller which is generating the error:

$twig = new \Kenjis\CI4Twig\Twig();
$render = $twig->render($templatename, $templatedata);

Any ideas what i'm doing wrong?!?
Thanks in advance!

Using Custom helper in View

I have a Custom helper
MY_string_helper.php

function startsWith($haystack, $needle) {
   // search backwards starting from haystack length characters from the end
   return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

So I use it with PHP

            if(startsWith($j, 'http'))
                echo '<script type="text/javascript" src="'.$j.'"></script>';
           else
                echo '<script type="text/javascript" src="'.base_url($j).'"></script>';
        <}

But with "twig", I can not use this function in the view to include the javascript file

My controller

 public function index(){
         $this->data['js'] = 'public/js/front/file'.js'
        $this->twig->display('front/index',  $this->data);
 }

I'm just looking for some help, thanks.

using another helper on codeigniter-ss-twig

Hi,
I want using codeigniter-ss-twig for personal project. this suport another helper of codeigniter for sample form form_input or form_password.
by using codeigniter-ss-twig I can using all features of twig ?

Unable to use functions

Running CI 3.1.4 with latest codeigniter-ss-twig plugin using Twig 1.33.2. Twig templates render great, however, I am unable to call methods.

{{ site_url('/') }} yields the following error Message: Unknown "site_url" function.

Same occurs with other functions such as form_open.

AddExtension

Hello,
How do I add extensions?
In trying, I encounter a 500 error.

Thank you

Sensiolabs security checker says the twig version you are using has a vulnerability

$ vendor/bin/security-checker security:check composer.lock
Symfony Security Check Report
=============================

1 packages have known vulnerabilities.

twig/twig (v1.37.1)
-------------------

 * [CVE-NONE-0001][]: Sandbox Information Disclosure

[CVE-NONE-0001]: https://symfony.com/blog/twig-sandbox-information-disclosure

Note that this checker can only detect vulnerabilities that are referenced in the SensioLabs security advisories database.
Execute this command regularly to check the newly discovered vulnerabilities.

Related with Session Data in twig Templates

Actually not an issue, but It will be a great help if you guide on this question.
How can we use $this->session->set_flashdata(), $this->session->set_userdata() and other session data in our twig templates?

I have tried something like this one:

$datasession = array(
    'nick' => $sess_nick,
    'login_ok' => true
);
$this->session->set_userdata($datasession);
$this->twig->addGlobal("session", $this->session);

and in twig template {{ session.userdata.nick }}
but not working!!!

Support constant

Hi Kenjis,
Thank you for your very good plugin, after having tested many, it is the only one that meets my needs and works perfectly.
But how can I add the addconstant (addGlobal()) support, if I write in my controller : $this->twig->addGlobal ('', '') , method is not defined.

I tried to add this in your extension :

    public function addGlobal($name, $value)
    {
        $this->createTwig();
        return $this->twig->addGlobal($name, $value);
    }

without success (I think the problem is that the object is redefined as "render" is called, but you know that better than me ^^)

Could you add this feature?
Thank you and sorry again for my translation

Error with phpunit

I'm using your package for phpunit integration with codeigniter 3.0, but i have problems run tests.
PHP Fatal error: Class 'Twig_Loader_Filesystem' not found in /var/www/html/project/application/libraries/Twig.php on line 35.
I also am using your package for secure integration of twig in codeigniter 3.0.
Any ideas?

Edit: I solved it adding require_once('../../vendor/autoload.php'); in Bootstrap.php, sorry but my bad english.

The invocation of `Kenjis\CI4Twig\Twig` results in the error message: "Call to a member function render() on null."

I am very much asking for advice on how to resolve the following error:
"Call to a member function render() on null."

This issue arises when calling it in the following manner:

<?php
namespace App\Controllers;

use App\Libraries\MyEasyTaskScheduler;
use App\Controllers\GetSystem;

class TaskScheduler extends BaseController
{
    private $taskScheduler;

    public function __construct()
    {
        $this->taskScheduler = new MyEasyTaskScheduler();
    }

    public function runTask()
    {
        $this->taskScheduler->named('genStaticPage')
        ->callTask(function(){
            (new GetSystem)->genStaticPage();
        })
        ->nextRun('+1 hour');
    }
}

Here's some additional information:

  1. Controller and Method Behavior:

    • The GetSystem controller and its genStaticPage method work correctly when used in the standard way.
    • For instance, if you add the following route to test/app/Config/Routes.php:
      $routes->get('gen_static\.html', 'GetSystem::genStaticPage');
      and then access http://my-test.dev/gen_static.html, everything functions as expected.
  2. Class Initialization and Variable Assignment:

    • Your class is initialized in the BaseController within the initController function and assigned to the variable: protected $twig;.
    • Out of curiosity, I added the following code snippet to the genStaticPage function in the GetSystem class:
      var_dump($this->twig);
      When called in the manner described in Info 1, it returns the complete data for the Twig class. However, when called in the way that triggers the error, it only returns NULL NULL NULL NULL NULL NULL NULL.
  3. MyEasyTaskScheduler Code Fragment:
    Below is a snippet from the MyEasyTaskScheduler library responsible for executing code:

    <?php
    
    class MyEasyTaskScheduler {
        // Other code
        public function callTask($callback)
        {
            $this->callback = $callback;
            return $this;
        }
        // More code
        private function executeCallback()
        {
            if ($this->callback instanceof Closure)
            {
                // Invoke the function passed as a closure
                return $this->callback->__invoke();
            }
    
            // Return null
            return null;
        }
        // Additional code
    }

Please help me with this problem.

unable to add codeigniter function at twig

Hi i am using this library but facing a problem while trying to use functions. Question on SO is not mine but i am facing same problem. i have already loaded url and form helpers in my controller.
I hope someone can help.

my error

n uncaught Exception was encountered

Type: LogicException

Message: Unable to add function "base_url" as extensions have already been initialized.

http://stackoverflow.com/questions/41662788/unable-to-add-codeigniter-function-at-twig (reffered from SO)

Adding filters

Hi,
I'm using your library in a non-CI app (native php) since a while now and it works great.

As I'm moving the app to php 8.0 I've updated your library to 4.1 and saw that Filters are no longer supported.
Is there any particular reason ?

I have a very large number of views and can't switch all filters to functions.
As Twig 3.3 still use filters, I tried to implements addFilter as you did for addFunction and it works like a charm.

So if there is no particular reason for removing addFilter in your lib I can submit a pull Request whit AddFilter functionality.

If this a duplicate of #20 sorry I was not sure.

Regards.

Register all user defined functions

Hi I'm trying to register all user defined functions in twig but it seems not to work.
Here's my approach:

			// begins here
		        $this->CI =& get_instance();
			$this->CI->load->helper('array');

			 foreach ( element('user', get_defined_functions()) as $v){
				//echo $v;
				//echo 
				$this->funcx($v);
			}
					
		/**
		* Register a function in Twig environment
		*
		**/
			 public function funcx($name)
    {
        $this->twig->addFunction(
        new Twig_SimpleFunction(
        $name,
        $name
        ));
        
        return $this;
    }
// ends here

I have defined functions such as script() assets() doo() inside a helper file which has been loaded.
In my template I used {{ doo() }} as an example but I get this error message :

//begins here
An uncaught Exception was encountered

Type: Twig_Error_Syntax

Message: Unknown "doo" function.
// ends here

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.