hello,

I have a paragraph text field where user will enter text.  In between some headers, I want to insert a variable that is created in the subtheme file.  For example, in the paragraph there is :

 Header

paragraphs

{{ my variable }} - I want to put this anywhere within the text.

More text

Initially, I had the variable placed at the end of the paragraph, but I realized that the users will want to place the variable anywhere they want inside the paragraph.

I thought that I could have them enter something in the content, like '*special field *' wherever they want this variable placed.

I tried using the str_replace and replace functions. I am still working on this, and still looking for solutions, but I thought I'd ask if I am on the right track. Does this sound like something that can be done? 

Comments

jaypan’s picture

There are two Drupal concepts you need to understand, and there is a module that brings these together.

The first concept is text formats. When creating fields on a Drupal entity, there are 'text, formatted' types. The formatted part is the relevant part. When a field is set to use text formatted, any textarea that takes data automatically comes with a field call the 'text format'. An example is the body of nodes - all nodes are long text formatted. What text formats do is that when the text is saved, it is passed through the text format. The text format is a series of rules, individually called input formats, that alter the saved text according to each rule. When you install Drupal with the default profile, it installs two text formats - Full HTML and Basic HTML. The text formats installed on your system can be seen at Admin -> Configuration -> Content Authoring -> Text Formats and Editors.

The other concept is tokens. You are trying to create a token. Drupal has a robust Token API, which you can extend with your own tokens either through code, or using a module.  

You can tie these two concepts together with the Token Filter module. When this module is enabled, each text format configuration gets an additional checkbox titled 'Replaces global and entity tokens with their values'. This filter goes through the text, and looks for an tokens in the Drupal token API format, and replaces them with the value.

So you can create custom tokens, enabled the token filter on a given text format, then use that text format with the textarea when creating your content. The content will be parsed for any tokens, including your custom tokens, and the values will be inserted.

Contact me to contract me for D7 -> D10/11 migrations.

maggieGin’s picture

Thank you for this great explanation.