我有像这样的NodeSeq
val article_template =
<div>
<div class="title"></div>
<div class="content"></div>
<!-- some other markups don't know -->
</div>
我想为List中的每篇文章创建此结构(定义为val articleList
),结果如下:
<div>
<div class="title">title a</div>
<div class="content">content a</div>
<!-- some other markups don't know -->
</div>
<div>
<div class="title">title b</div>
<div class="content">content b</div>
<!-- some other markups don't know -->
</div>
...
已更新:
请注意<!-- some other markups don't know -->
部分,
所以我不能使用XML文字语法来构造它。
我需要一个修改后的article_template
列表以及相应的文章信息。
答案 0 :(得分:3)
答案 1 :(得分:3)
这是lift对
非常有用的东西import net.liftweb.util.Helpers._
case class Article( title: String, content: String )
val articles = List(
Article("title a","content a"),
Article("title b","content b")
)
val snipet =
"article *" #> articles.map { article =>
"header h1 *" #> article.title &
".content *" #> article.content
}
val article_template =
<article>
<header>
<h1>Title</h1>
</header>
<section class="content">
Content
</section>
</article>
snipet( article_template )
答案 2 :(得分:1)
您可以使用Group对XML元素进行分组。在XML文字中,它将如下所示:
val xml =
<xml:group>
<div>
<div class="title">title a</div>
<div class="content">content a</div>
</div>
<div>
<div class="title">title b</div>
<div class="content">content b</div>
</div>
</xml:group>
您可以像这样动态创建XML:
case class Article(title: String, content: String)
val articles = List(Article("A1", "A1 content"), Article("A2", "A2 content"))
val xml =
<xml:group>{articles map { a =>
<div>
<div class="title">{a title}</div>
<div class="content">{a content}</div>
</div>
}}</xml:group>
这是使用模板的另一种变体。模板只是一个返回XML的函数。在这种情况下,我使用currying来生成每篇文章的模板列表(仍然需要提供一些东西):
case class Article(title: String, content: String)
val articles = List(Article("A1", "A1 content"), Article("A2", "A2 content"))
def articleTemplate[T](article: Article)(stuff: T) =
<div>
<div class="title">{article title}</div>
<div class="content">{article content}</div>
<div class="stuff">{stuff}</div>
</div>
val allArticles = articles map articleTemplate
val allArticlesWithStuff: NodeSeq =
allArticles.zipWithIndex map {case (f, i) => f(i)}
答案 3 :(得分:1)
假设Article
的定义类似于:
case class Article(title: String, content: String)
和articleList
as:
val articleList = List(
Article("title a","content a"),
Article("title b", "content b"))
您可以使用以下命令生成XML片段:
val xml: scala.xml.NodeSeq = articleList map { article =>
<div>
<div class="title">{article.title}</div>
<div class="content">{article.content}</div>
</div>
}
答案 4 :(得分:0)
使用flatmap将它们添加到一起:
val xml: NodeSeq = List("Test", "Something", "Yo").flatMap(s => <a>{s}</a>)
更新:适用于匹配
val xml: NodeSeq = List("Test", "Something", "Yo", 1).flatMap{
case s: String => <string>{s}</string>
case i: Int => <int>{i}</int>
}