html

Q&A's, tips, howto's
Locked
eddier
Posts: 289
Joined: Mon Oct 07, 2002 2:48 pm
Location: Blue Mountain College, MS US

html

Post by eddier »

Kind of a macro within macro within ... thingy that really helps with html code.

Code: Select all

(define (<page> %w)
  (replace "`(.+?)`" %w (string (eval-string $1)) 516)
  (if (> $0 0) (<page> %w) %w))

...

(let (isfred true val "fred")
  (print [text]Content-type: text/html

<html>
<body>
<p>`(if test
              "Hello `val`!"
              "You are not `val`!")`</p>
</body>
</html>[/text]))
Three things to notice,
1. Lutz was right about using 512 in replace when nesting. Notice `val` nested within the `(if ...)`
2. I added 4 because I needed to match across newlines.
3. I didn't see a post-test loop for newlisp in reference manual. I was fooled by (until ) until I noticed that it meant (while (not ... Still a pre-test loop. The recursive version of (<page> %w) would be a one liner using something like

Code: Select all

(define (<page> %w)
  (repeat (> $0 0) (replace "`(.+?)`" %w (string (eval-string $1)) 516)))
Would a post-test loop construct be usefull for anyone else? I try to stay functional for the most part, but here, an imperative construct seems to be most natural.

What do you think Lutz?

Eddie

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

Looking into the code, it would be trivial to add, it could be 'do-while' and 'do-until' for post-test versions of 'while' and 'until'. Occasionally I also felt the urge to have it.

But I wonder how others feel about it?

Lutz

lwix
Posts: 24
Joined: Tue Oct 26, 2004 3:14 am
Location: New Zealand

Post by lwix »

+1 (i.e. "yes" to having them added)
small's beautiful

eddier
Posts: 289
Joined: Mon Oct 07, 2002 2:48 pm
Location: Blue Mountain College, MS US

Post by eddier »

Correction. To handle both nesting of "<% %>"s and sequences of "<% %>"s, change the substitute code to

Code: Select all

(define (subs %w)
  (replace "(<%([^<%]+?)%>)" %w (string (eval-string $2)) 0)
  (if (> $0 0) (subs %w) %w))

(setq iftest true dotrue "hello" dofalse "goodbye")
(setq text [text]<p><%(if <%iftest%> "<%dotrue%>" "<%dofalse%>")%></p>[/text])

(println (subs text))

(exit)
=> "<p>hello</p>"
Note the only non-greedy part should be inside of the closest "<% %>" pairs, not outside.

Eddie

eddier
Posts: 289
Joined: Mon Oct 07, 2002 2:48 pm
Location: Blue Mountain College, MS US

Post by eddier »

OOPS! Use the following.

Code: Select all

(define (subs w)
  (replace "<%([^<%]+?)%>" w (string (eval-string $1)) 0)
  (if (> $0 0) (subs w) w))
Eddie

Locked