Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
It'd be useful if there was a way of trimming the output of tokens to a specific length, e.g. [node:title:100] to trim the node title to 100 characters.
Comments
Comment #1
Dave ReidUnfortunately there's not a way for the Token API to reliably do this. Individual modules should use the 'callback' option of the token_replace() method to alter/trim/manipulate the tokens before string replacement is done.
Comment #2
DamienMcKennaMaybe by adding hook_token_info_alter() to add an optional ":trim:X" argument on every token, similar to how Imagecache_Token does image field attributes? A little crazy, yes, but technically feasible, right?
Comment #3
Dave ReidIt's a lot more technically complicated than that. We have to consider the performance of the token tree, form validation, how many tokens would get this support. It ends up being a much harder and larger can of worms.
However, I would encourage experimentation. If another module proves it is possible and is fully integrated to all the aspects of the Token module (validation, UI, etc), I would be more than happy to assist with merging it upstream. While I leave this issue closed simply because it's just not something we can support or spend time actively working on, if someone opens this or a new issue with a valid patch, I will give it due consideration.
Comment #4
DamienMcKennaThanks Dave. BTW this request came from #2300173: How to get a meta tag summary without the body field? originally.
Comment #5
Yannick PerretThis is an old thread, but for the record we did that by creating a new token [node:trim:LENGTH:FIELD]. The idea is simple: node:trim gets the length, then build the "original" token without the trim stuff ([node:FIELD]), calls
token_generate()
to get field value, and then applies triming.Raw code (to be improved, probably) looks like:
This is raw code, extracted from our code (so some parts may be erroneous, and it misses some sanity checks), but it works fine.
We use this to trim title size when generating mails subjects (via rules).
Hope it can help other people.