slugify
slugify copied to clipboard
Twig Bridge - no functionality to add rule
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,
You should call addRules()
on the Slugify object before you inject it to the Cocur\Slugify\Bridge\Twig\SlugifyExtension
constructor.
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,
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 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 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 Putting this kind of logic inside your template seems like a good idea to get unmanageable code.