trix
trix copied to clipboard
How would you use variables in Trix, if possible?
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
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?
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 😀
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?
I am adding a screenshot which shows the content
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:
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
)