Created
January 4, 2013 04:52
-
-
Save agrif/4450022 to your computer and use it in GitHub Desktop.
a simple scheme example to output HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; helper to let us know when a symbol starts with : | |
(define attr? | |
(lambda (sym) | |
(and (symbol? sym) | |
(eq? #\: (string-ref (symbol->string sym) 0))))) | |
; handles tag contents, and the end tag | |
(define (tag-finish name args) | |
(if (null? args) | |
`((display "</") | |
(display ,name) | |
(display ">")) | |
(if (list? (car args)) | |
`(,(car args) ,@ (tag-finish name (cdr args))) | |
`((display ,(car args)) ,@ (tag-finish name (cdr args)))))) | |
; handles attributes, and the /> if there is no | |
; tag contents, otherwise calls tag-finish | |
(define (tag-attrs name args) | |
(if (and | |
(not (null? args)) | |
(attr? (car args)) | |
(not (null? (cdr args)))) | |
(let* ((attrsym (symbol->string (car args))) | |
(attr (substring attrsym 1 (string-length attrsym))) | |
(value (cadr args))) | |
`((display " ") | |
(display ,attr) | |
(display "=\"") | |
(display ,value) | |
(display "\"") ,@ (tag-attrs name (cddr args)))) | |
(if (null? args) | |
'((display "/>")) | |
`((display ">") ,@ (tag-finish name args))))) | |
; handles the opening tag, minus >, and calls tag-attrs | |
(define (tag-begin name args) | |
`(begin (display "<") | |
(display ,name) ,@ (tag-attrs name args))) | |
; a macro that auto-defines a symbol to be a macro | |
; that calls out to tag-begin. | |
; you heard that right. | |
(define-macro (define-tag name) | |
`(define-macro (,name . args) | |
(tag-begin ,(symbol->string name) args))) | |
;; demo code below | |
;; =============== | |
(define-tag p) | |
(define-tag strong) | |
(define-tag a) | |
(define-tag br) | |
(define test-val 5) | |
(p "the value is " (strong test-val)) | |
(br) | |
(a :href "http://google.com/" "this is google") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment