Edgewall Software

Version 4 (modified by cmlenz, 18 years ago) (diff)

Only match text input fields

Genshi Recipes: Automatically Populating an HTML Form

The following template provides a match template that automatically adds a value attribute to any <input> element that has matching data in the context.

<html xmlns:py="http://genshi.edgewall.org/">
 
  <input py:match="form//input[@type='text']" py:attrs="select('@*')"
         value="${form[str(select('@name'))]}" />
 
  <form action="" method="POST">
    <p>
      <label>Something: <input type="text" name="something"/></label>
    </p>
  </form>
</html>

Assuming the context data contained a variable “form” that was {'something': 'Look, Ma'}, the output would look as follows:

<html>
  <form action="" method="POST">
    <p>
      <label>Something: <input value="Look, Ma" type="text" name="something" /></label>
    </p>
    <input value="Send" type="submit" />
  </form>
</html>

This recipe would need to be extended to also support checkboxes, select fields, and so on.


See also: GenshiRecipes, Genshi XML Template Language