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

Dave Reid’s picture

Status: Active » Closed (won't fix)

Unfortunately 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.

DamienMcKenna’s picture

Maybe 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?

Dave Reid’s picture

It'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.

DamienMcKenna’s picture

Yannick Perret’s picture

This 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:

function HOOK_token_info() {
  $info['tokens']['node']['trim'] = array(
    'name' => t('Trim node token'),
    'description' => t('Returns following token(s) trimed by given length'),
  );
  return $info;
}

function HOOK_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if (($type == 'node')) {
    foreach($tokens as $name => $original) {
      $clang = explode(":", $name);
      if ($clang[0] == 'trim') {
        // get trim length
        $length = $clang[1];
        if (!is_numeric($length)) {
          continue; // skip: not a number
        }
        // we need remaining data
        if (!isset($clang[2])) {
          continue;
        }
        array_shift($clang);
        array_shift($clang);
        $ltoken = [ implode(":", $clang) => $original ];
        $tmp = token_generate('node', $ltoken, $data, $options);
        foreach($tmp as $id => $val) {
          $replacements[$id] = function_to_cut_string($val, $length);
        }
    }
  }
}

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.