Devon Bessemer
Devon Bessemer

Reputation: 35347

XSL foreach attributes as HTML input attributes

Okay, I'm trying to be able to dynamically set the input attributes via an XML tag. For example:

<text name='text_name' value='text_value'>text_display</text>

I want to run a foreach to make it so name, value, or any other attribute in <text> will be inserted as an attribute for the HTML input and use the value of the <text> as the label/placeholder.

<xsl:for-each select="text">
    <label><xsl:value-of select="." /></label>
    <input type='textfield' placeholder='{.}' />
</xsl:for-each>

Now I know I can use:

<xsl:for-each select="@*"> 

but I don't know how to insert that into the input tag.

Thanks in advance for any advice.

Upvotes: 1

Views: 951

Answers (1)

user764357
user764357

Reputation:

Try and use push focused (rather than pull-focused) XSLTs with more apply-templates and less for-each statements.

There is nothing that says the definition of an element or its attributes must be in the same template. So when you make the template for the <text> element, you can just create the <input> element and apply-templates over all of the attributes.

<xsl:template match="text">
 <input>
  <xsl:apply-templates select="@*"/>
  <label><xsl:value-of select="." /></label>
 </input>
</xsl:template>

Secondly, what you are trying to do is literally copy the attributes into the new document, so rather than recreate them, just copy them, like so:

<xsl:template match="text/@*">
  <xsl:copy/>
</xsl:template>

So, here is a complete stylesheet...

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/texts">
 <xsl:apply-templates />
</xsl:template>

<xsl:template match="text">
 <input>
  <xsl:apply-templates select="@*"/>
  <label><xsl:value-of select="." /></label>
 </input>
</xsl:template>

<xsl:template match="text/@*">
  <xsl:copy/>
</xsl:template>

</xsl:stylesheet>

... when applied to this input XML document...

<texts>
  <text name='text_name' value='text_value'>text_display</text>
  <text name='text_name2' value='text_value2'>other_display</text>
</texts>

... gives this result XML

<input name="text_name" value="text_value">
    <label>text_display</label>
</input>
<input name="text_name2" value="text_value2">
    <label>other_display</label>
</input>

Upvotes: 2

Related Questions