slugify icon indicating copy to clipboard operation
slugify copied to clipboard

Twig Bridge - no functionality to add rule

Open harsain opened this issue 8 years ago • 6 comments

As per the documentation, slugify has a method addRule which we can call to add custom rules, same is not available via twig bridge. We have a use-case where we want to use the filter with a custom filter. So I started looking at the code base and seems it can be done with a small change to the SlugifyExtension. I have got it working on my environment and just wanted to your views before I submit a pull request. Use-Case: We have words like "Snacks & Bars", which we want to be converted to "snacks-and-bar". Using Slugify class it can be easily done by using the method addRule('&', 'and'), but we are using it in the twig as a filter.

So the change will be as follows:

public function slugifyFilter($string, $separator = null, $newRules = [])
    {
	    if (! empty($newRules)) {
		    $this->slugify->addRules($newRules);
	    }
	    return $this->slugify->slugify($string, $separator);
    }

Regards,

harsain avatar Jan 19 '17 22:01 harsain

You should call addRules() on the Slugify object before you inject it to the Cocur\Slugify\Bridge\Twig\SlugifyExtension constructor.

florianeckerstorfer avatar Feb 09 '17 19:02 florianeckerstorfer

That's correct. but will only work if we know the rule to be added. instead the scenario i am talking about is when the rule is not known and will be passed from the twig template.

So something like:

{{name | slugify(null, {'&': 'and'}) }}

As, you can see here the php level code doesn't know the rule but will be passed from template

Regards,

harsain avatar Feb 10 '17 03:02 harsain

This configuration would also be appreciated on SF bridge.

Something like this or anything that allow us to addRule for simple cases.

cocur_slugify:
    separator: "_"
    rulesets:
        - default
        - [".",""]

nei avatar Feb 10 '17 17:02 nei

@nei This would be the correct approach for solving this.

When we are talking about just the Twig integration because it could be part of the SF bridge, but it could also mean just straight-up Twig.

Alternatively for Twig we could add a slugfiy_add_rule tag to allow editing rules. I would prefer not to change the call for slugify because I think it should match the PHP methods signature.

florianeckerstorfer avatar Feb 11 '17 12:02 florianeckerstorfer

@florianeckerstorfer adding a tag would be a better option ...

I was more talking about the scenario where the Frontend guys don't know anything about the backend and have no knowledge about the configurations, in that scenario they can just pass and new rules directly from the twig template and no change in the backend will be required

harsain avatar Feb 14 '17 00:02 harsain

@harsain Putting this kind of logic inside your template seems like a good idea to get unmanageable code.

Pazns avatar Jun 17 '18 13:06 Pazns