0

Given a String list

val www = List("http://bloomberg.com", "http://marketwatch.com");

I want to dynamically generate

<span id="span1">http://bloomberg.com</span>
<span id="span2">http://marketwatch.com</span>

def genSpan(web: String) = <span id="span1"> + web + </span>;

www.map(genSpan); // How can I pass the loop index?

How can I use the Scala map function to generate the ids (span1, span2), as 1 and 2 are the loop indexes? Or is the only way is to use for comprehension?

1 Answer 1

5

The easiest way is to use zipWithIndex which turns a list into a list of tuples (value,index). In your case,

def genSpan(web: String, id: Int) = {
  <span id={ "span%d".format(id) }> { web } </span>
}
www.zipWithIndex.map(x => genSpan(x._1,x._2+1))

Note that the index, x._2, starts from zero but you want to start from one, so I added one in the call to genSpan. Note also that you can set attributes using Scala code by wrapping the Scala code in {}.

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

2 Comments

need to wrap "web" as well, <span id={ "span%d".format(id) }> + {web} + </span> Thanks!
@portoalet - Yes, whoops! Fixed now. (No + by the way--everything inside the XML block is output.)

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.