conditional elements

2 views
Skip to first unread message

Terrence Brannon

unread,
Oct 3, 2008, 2:58:18 PM10/3/08
to Nagare users
What do you provide if you want nothing added to the HTML in a
particular case... below, I try to add a "World" to the document only
if the random number is less than 0.5, but the pass is failing:

from nagare.namespaces import xhtml
import random

def maybe_world():
if random.random() < 0.5:
h.h1("World").meld_id("world_node")
else:
pass

h = xhtml.Renderer()

tree = h.html(
h.body(
h.h1("Hello").meld_id("title"),
maybe_world()
)
)

print tree
print tree.write_xmlstring(pretty_print=True)
Message has been deleted

apoirier

unread,
Oct 3, 2008, 4:12:33 PM10/3/08
to Nagare users
On Oct 3, 8:58 pm, Terrence Brannon <metap...@gmail.com> wrote:
> What do you provide if you want nothing added to the HTML in a
> particular case...

You can return an empty string, an empty tuple of nodes or an
empy list of nodes.

> below, I try to add a "World" to the document only
> if the random number is less than 0.5, but the pass is failing:
>
> from nagare.namespaces import xhtml
> import random
>
> def maybe_world():
>     if random.random() < 0.5:
>         h.h1("World").meld_id("world_node")

h.h1("World") only creates a new node but doesn't insert
it into the DOM. You need to return it.

>     else:
>         pass
>
> h = xhtml.Renderer()
>
> tree = h.html(
>     h.body(
>         h.h1("Hello").meld_id("title"),
>         maybe_world()
>         )
>     )
>
> print tree
> print tree.write_xmlstring(pretty_print=True)

import random

from nagare.namespaces import xhtml
h = xhtml.Renderer()

def maybe_world():
if random.random() < 0.5:
return h.h1("World").meld_id("world_node")
else:
return '' # or `()` or `[}`

tree = h.html(
h.body(
h.h1("Hello").meld_id("title"),
maybe_world()
)
)

print tree.write_xmlstring(pretty_print=True)
Reply all
Reply to author
Forward
0 new messages