0

Looking for a way to add a token/replacement pattern into shortcode.

For example, creating a button where different text and link is required depending on other factors - something like the following:

[button link="mysite/[url replacement pattern]" text="[label replacement pattern]"][/button]

The main reason I need to do this is that I'm using view field views and want to replace an empty field with a custom button, contained in the 'sub view' when the view is empty, which needs to be different depending on what should be in the 'sub view' - I'm using shortcodes in with Global: Text Area in the No Results Behaviour (if that makes sense)

Unless, of course, anyone knows another way to achieve the same result.

0

Ok, seems there are some limited ways to do this, using available replacement patterns that are not contained within square brackets. i.e. %1 and !1, but not [replacement pattern]

Luck would have it, the replacements I need are the %1 and !1 values.

Still - would be great if anyone had any ideas how to use square bracketed replacement patterns in shortcodes without closing the shortcode (which is what appears to happen).

0

You can use Token filter which will add a Text format filter for token replacement. They you simply need to make sure the Token filter will run before the Shortcode one. More specifically:

  1. Install Token filter
  2. Go to admin/config/content/formats
  3. Click "Configure" for the text format you are using.
  4. Enable the Token replacement and the Shortcodes filters under "Enabled Filters"
  5. Under "Filter processing order" make sure that Token replacement precedes Shortcodes

This will ensure that the tokens will be replaced before the shortcodes are parsed and will therefore work as expected.

Bonus:

In case you are using any sort of Visual Shortcodes, adding [ or ] as content will most likely confuse the editor (in my case they were replaced with |LS| and |RS| respectively).

In that case you can set up a pre-render hook where you can change back those specific strings (or any other you might use to wrap tokens with), e.g. for blocks it could be something like that (for Drupal 8)

/**
 * Implements hook_entity_view_alter().    
 */
function my_module_entity_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = 'my_module_replace_token_wrappers';
}

function my_module_replace_token_wrappers(array $build) {
  // Get the body
  $body = &$build['content']['body'][0]['#text'];
  // Replace the values of |LS|/|RS| with [\] respectively
  $body = str_replace('|LS|', '[', $body);
  $body = str_replace('|RS|', ']', $body);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.