0

I want to customize a message where from the back end the user can modify a Welcome Message. Something like:

Welcome to #{userInfo["name"]}, out latest member

Where userInfo["name"] is a GET Variable.

I store this message on a model column called welcomeMsj.

Then I am trying to display the message using the model. Something like:

messages = Model.first

puts messages.welcomeMessage

I have an output like:

Welcome to #{userInfo["name"]}, out latest member

But I want to display:

Welcome to Emmanuel, out latest member

What's the correct syntax for this?

Thanks in advance.

1
  • Are you using erb in your view? Commented Apr 15, 2015 at 0:29

2 Answers 2

1

The Liquid template engine was created just for this kind of use case. You could have the backend user include a special string in double curly braces such as {{name}} that you then populate at render time. For example, the backend user would set the welcome message to "Welcome to {{name}}, our latest member." which would be stored in your database. Assuming that the current_user variable represents the user that's currently logged in, you could render the customized message with the following code:

template = Liquid::Template.parse(messages.welcomeMessage) 
template.render('name' => current_user.name)              

Another, more dangerous strategy is to use eval which will interpret the string as code:

puts eval("\"" + messages.welcomeMessage + "\"")

This isn't recommended because it could allow a malicious user to run arbitrary code. By using Liquid, you maintain control of the exact value that gets used in place of {{name}}.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Welcome to <%= userInfo["name"] %>, our latest member

1 Comment

This wouldn't automagically work, though. The other part of the solution is missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.