trix icon indicating copy to clipboard operation
trix copied to clipboard

How would you use variables in Trix, if possible?

Open viktorsmari opened this issue 2 years ago • 6 comments

If we allow our users to add variables inside the Trix field, like this:

{{some_variable}}

That could map to something like @user.first_name

How can we replace the Trix text for example with .gsub - on which attribute object should we apply it?

It has been asked here, I had the same ActionText::RichText error: https://stackoverflow.com/questions/65327776/embedding-variable-inside-text-using-trix?noredirect=1#comment129433161_65327776

viktorsmari avatar Aug 09 '22 14:08 viktorsmari

We use Shopify liquid for that. Either Liquid.js or Ruby gem.

mech avatar Aug 16 '22 11:08 mech

Are you able to use Shopify liquid directly with Trix? Do you have an example code or gist?

I tried using .gsub but had the same issue as I linked to in the StackOverflow post, I cannot do a .gsub on a ActionText::RichText object, I thought Liquid would have the same issues?

viktorsmari avatar Aug 16 '22 11:08 viktorsmari

Unfortunately I don't have a gist so far. From what I know ActionText::RichText give you back the HTML string using either to_s or to_trix_html and you can use that HTML which contain variables for you to replace:

html = your_model.to_trix_html
variables = {
  "user" => @user
}
Liquid::Template.parse(html).render(variables)

Not sure if this is what you have in mind.

If you want to straightaway replace within the Trix editor in-place, then perhaps can find usage in TrixAttachment there 😀

mech avatar Aug 16 '22 12:08 mech

Thanks for that @mech

When I use the your_model.to_trix_html it works, I get the correct variable, but attached images (ActiveStorage Amazon S3) are not showing :thinking:

I am using your example and using simple_format

simple_format Liquid::Template.parse(html).render(variables)

Should I be using something else?

viktorsmari avatar Aug 16 '22 17:08 viktorsmari

I am adding a screenshot which shows the content 2022-08-16_19-37-48

First is only the page.content Then the Liquid without the to_trix_html

<%= simple_format Liquid::Template.parse(page.content).render(variables) %>

Now it shows the image, however the formatting looks off, compared to the page.content The image is now left aligned, instead of centered, and there is a lot of spacing below the image. :thinking:

viktorsmari avatar Aug 16 '22 17:08 viktorsmari

I get the correct behavior if I use .html_safe:

<%= Liquid::Template.parse(page.content).render(variables).html_safe %>

Is that OK, or should I use a different approach? (not using .to_trix_html)

viktorsmari avatar Aug 16 '22 18:08 viktorsmari