2017-10-05 63 views
0

生成帶有換行符編號列表,我有以下數據:如何,使用R晶須模板引擎

data <- list(name = "Chris", 
      children_names = c("Alex", "John") 
      ) 

基於R的模板引擎whisker,我想這個輸出, 渲染時:

I am Chris 
My children are: 
    Child No 1 is Alex 
    Child No 2 is John 

這是我當前的代碼:

library(whisker) 
template <- 
'I am {{name}} 
My children are: 
{{children_names}} 
' 

data <- list(name = "Chris", 
      children_names = c("Alex", "John") 

      ) 

text <- whisker.render(template, data) 
cat(text) 

# which produces: 

# I am Chris 
# My children are: 
# Alex,John 

w ^這不是我想要的。 什麼是正確的做法?

回答

1

你可能已經想通了這一點,但如果你沒有:

library(whisker) 

template <- 
    'I am {{name}} \n 
    My children are: \n 
    {{#children_names}} 
    Child No {{number}} is {{cname}} 
    {{/children_names}}' 

data <- list( 
    name = "Chris", 
    children_names = list(
    list(cname = "Alex", number = 1), list(cname = "John", number = 2) 
) 
) 

text <- whisker.render(template, data) 
cat(text) 

# I am Chris 
# 
# My children are: 
# 
# Child No 1 is Alex 
# Child No 2 is John