2

I would like to let users use variable name inside text box with Trix.

Given a trix text-box that let the user write messages to other user, I would like to be able to do something like this: "Hello %user_name%"

When sending the message the user_name would be changed to whatever is the user_name.

I would except this to be a fairly standard feature but couldn't find mention of it in the documentation or SO.

I have tried doing a simple .gsub on the model.content.body but this is returning and ActionText::RichText who doesn't know what gsub is.

Yann
  • 43
  • 1
  • 5

1 Answers1

0

An easy way to mock variables within text contents is to use search and replace, just replace the strings within the action that receives posted contents:

final_message = params[:message].gsub("%user_name%", "John Doe")

Note that gsub is only available for string type.

Farhad
  • 803
  • 4
  • 8
  • 20
  • Thanks for your answer. I should have specified but the saved message is a template that will be sent to many users later on. Therefore I can not replace when receiving the message from the params. I also tried a similar approach on the Trix object but it doesn't yield a string but a RichtText object. – Yann Dec 17 '20 at 07:57