简体   繁体   中英

Ruby/Rails: Parsing and inserting partials into text

Suppose I have a body of text (string) like this:

str = 'This is some text. {insertion_1} And this is also some text. {insertion_2}'

The contents of the two curly braces represent a model ( Insertion ) and its ID. The ultimate goal is to parse the string, and replace the curly braced "insertions" with an insertion partial. The insertion partial will simply be a line or two of HTML.

If the insertions were static I could do something like str.gsub!(/\\{insertion_\\d*\\}/, 'some content') , but I need to parse the insertions one-by-one, to insert the appropriate data. Can anyone suggest a best practice for handling a situation like this?

EDIT: I should have mentioned, this is for a WYSIWYG. The end user selects from a list of "insertions" and once selected, it adds the appropriate {insertion_id} placeholder into the body of their post, which will be parsed out later to insert the right content.

You can use regexp captures and gsub with a block to accomplish what you want, like this:

str = 'This is some text. {insertion_1} And this is also some text. {insertion_2}'

replacements = {
  1 => 'HELLO',
  2 => 'WORLD',
}

str.gsub(/\{insertion_(\d*)\}/) {
  id = $1.to_i
  replacements[id]
}
# => "This is some text. HELLO And this is also some text. WORLD" 

Just replace the block body with whatever you need to do. :)

(Sidenote: \\d+ is a better choice than \\d* for matching numbers.)

You could... use partials, and provide data. Those may also be rendered to a string using render_to_string .

You could use raw Erb, which can parse strings; doesn't need to be a template on disk.

You could use normal string interpolation:

t1 = "ohai"
p "This is some text. #{t1}, kthxbai."

An alternative method is to use the %s in your string. Here's an example.

names = %w(chris john robert mike)
welcome = "Hello %s, %s would like to show you around. %s and %s are waiting in the other room" % names
# => "Hello chris, john would like to show you around. robert and mike are waiting in the other room"

If you need something bigger and more versatile than just plain old ruby style "foo #{bar} baz" you might want to look into liquid .

It basically works like erb, but you use {{ some_variable }} for your tags instead of <%= some_variable %> . It also has support for loops and custom tags and all sorts of nifty stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM