kenjis / codeigniter-ss-twig

A Simple and Secure Twig integration for CodeIgniter 3.x and 4.x
MIT License
168 stars 46 forks source link

Using Custom helper in View #32

Closed Edgargmc closed 7 years ago

Edgargmc commented 7 years ago

I have a Custom helper _MY_stringhelper.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.

kenjis commented 7 years ago

You have to register your helper to Twig. See https://github.com/kenjis/codeigniter-ss-twig#adding-your-functions.

Edgargmc commented 7 years ago

I tried to do what you tell me.

My Controller "Front.php"

class Front extends CI_Controller {
    const VIEW_JS = 'front';
    private $js_files = ['public/js/front/'.self::VIEW_JS.'.js'];
    private $data = [];

    public function __construct(){
        parent::__construct();
        $this->load->helper('String');
        $config = [
            'functions' => ['String']
        ];

        $this->load->library('twig', $config);
        $this->load->model('user');
        $this->data['js'] = $this->js_files;
    }

    public function index(){
        $this->twig->display('front/index',  $this->data);
    }
}

this is in my index.twig

{% if js is iterable %}
    {% for j in js %}
        {% if startsWith(js, 'http') %}

        {% endif %}

        <script type="text/javascript" src="{{ base_url(j) }}"></script>
    {% endfor %}

{% else %}

the result is

Message: Unknown "startsWith" function.

Filename: C:\wamp\www\code\application\views\Front\index.twig

Line Number: 29

/*****/ I tried to do the same in an html

In my index.twig

{% include './Front/Common/footer.html' %}

in my footer.html'

{% if js is iterable %}
    {% for j in js %}
        {% if startsWith(js, 'http') %}
            <script type="text/javascript" src="{{ base_url(j) }}"></script>
    {% endif %}

{% endfor %}

the result

Type: Twig_Error_Syntax

Message: Unknown "startsWith" function.

Filename: C:\wamp\www\code\application\views\Front\Common\footer.html

Line Number: 14

Any ideas please?

kenjis commented 7 years ago
        $config = [
            'functions' => ['String']
        ];

String should be startsWith.

Edgargmc commented 7 years ago

Thank you very much, that worked. Good job for this library Congratulations on your work.

Thanks for the help.