Edgewall Software

GenshiRecipes/FormFilling

Version 5 (modified by cmlenz, 8 years ago)

Add match templates for checkboxes, radio groups, and text areas

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.get(str(select('@name')))}" />
  <input py:match="form//input[@type='checkbox']" py:attrs="select('@*')"
         checked="${form.get(str(select('@name')))}" />
  <input py:match="form//input[@type='radio']" py:attrs="select('@*')"
         py:with="value = form.get(str(select('@name')))"
         selected="${value and (value == str(select('@value'))) or None}" />
  <textarea py:match="form//textarea" py:attrs="select('@*')"
            py:content="form.get(str(select('@name')))"></textarea>

  <form action="" method="POST">
    <!--! A simple text field -->
    <p>
      <label>Something: <input type="text" name="name"/></label>
    </p>
    <!--! A check box -->
    <p>
      <label>Enabled: <input type="checkbox" name="enable" /></label>
    </p>
    <!--! A text area -->
    <p>
      <label for="description">Description</label>
      <textarea id="description" name="description">Bla bla bla</textarea>
    </p>
    <!--! A radio group -->
    <fieldset>
      <legend>Select one:</legend>
      <label py:for="option in ('A', 'B', 'C')">
        <input type="radio" name="option" value="$option" />
      </label>
    </fieldset>
  </form>
</html>

Assuming the context data contained a variable “form” that was set to:

form = {'name': 'Look, Ma',
        'enable': '',
        'option': 'B',
        'description': 'This is the description someone put in here'}

Then the output would look as follows:

<html>
  <form action="" method="POST">
    <p>
      <label>Something: <input value="Look, Ma" type="text" name="name" /></label>
    </p>
    <p>
      <label>Enabled: <input type="checkbox" name="enable" /></label>
    </p>
    <p>
      <label for="description">Description</label>
      <textarea id="description" name="description">This is the description someone put in here</textarea>
    </p>
    <fieldset>
      <legend>Select one:</legend>
      <label>
        <input type="radio" name="option" value="A" />
      </label>
      <label>
        <input selected="selected" type="radio" name="option" value="B" />
      </label>
      <label>
        <input type="radio" name="option" value="C" />
      </label>
    </fieldset>
  </form>
</html>

This recipe would need to be extended to also support select fields.


See also: GenshiRecipes, Genshi XML Template Language