1

I'm using twig and Codeigniter and i'm trying to create links for a menu.

The link's names looks like this :

about_us, home, our_products_and_activities, send_us_feedback

My finale result should be :

about_us, home, our_products, send_us

How can i remove all after the second lower dash?

Here is what i've done so far ( a little messy but works partially )

 <ul class="sidebar-menu">

        {% for link in menu['links'] %}
            <li class="treeview">
                // remove spaces and added lower dashes instead
                {% set links_str = link.page_name|lower|replace({' 

                ':'_'})|striptags %}
                // breaks str to array
                {% set striped_links = links_str|split('_') %}

                // create new array from the portion i need
                {% set links_values = [striped_links.0,striped_links.1] %}

                // join them all and added lower dash
                {% set new_values = links_values|join('_') %}

                {{ dump(new_values) }}

           </li>
       {% endfor %}
</ul>

Now i get about_us, home_, our_products_, send_us_

I could remove the last lower dash... but i'm looking for more elegant way .

Thanks.

RoyBarOn
  • 919
  • 3
  • 24
  • 63

1 Answers1

1

Extend twig

$twig->addFilter(new Twig_SimpleFilter('break_on', function($value, $character, $position = 1) {
    return substr($value, 0, strposX($value, $character, $position));
});

Twig

{{ 'our_products_and_activities' | break_on('_', 2) }}

global function

function strposX($haystack, $needle, $number){
    if($number == 1){
        return strpos($haystack, $needle);
    }elseif($number > 1){
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    }else{
        return error_log('Error: Value for parameter $number is out of range');
    }
}

function by Smokey_Bud

Community
  • 1
  • 1
DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Thank for the quick reply - i never create custom filters before, where should i put the "extend twig" part? i've tried in the main controller – RoyBarOn Apr 04 '17 at 07:18
  • After where you register `twig`, don't know where codeigniter does this tho – DarkBee Apr 04 '17 at 07:29