Rebol: How to use local variables with inline markup function?

Is there a way to do this, including creating another markup function?

+2


source to share


2 answers


Unfortunately build-markup only uses global variables: the link text a> says: note that the variables used in tags are always global variables.

Here's a slightly looser way of doing it using an internal object ( bm-1 ) demonstrates the problem: a and b are printed with their global bm-2 values, which is a clumsy job):



a: "global-a"
b: "global-b"


bm-1: func [a b][
      print build-markup "<%a%> <%b%>"
   ]

bm-2: func [a b][
    cont: context [
       v-a: a
       v-b: b
       ]
      print build-markup "<%cont/v-a%> <%cont/v-b%>"
   ]

bm-1 "aaa" "bbb"
bm-2 "aaa" "bbb"

      

REBOL3 has the word , not build-markup . It is much more flexible.

+1


source


I fixed the markup function to be able to use local contexts:

build-markup: func [
    {Return markup text replacing <%tags%> with their evaluated results.}
    content [string! file! url!]
    /bind obj [object!] "Object to bind"    ;ability to run in a local context
    /quiet "Do not show errors in the output."
    /local out eval value
][
    content: either string? content [copy content] [read content]
    out: make string! 126
    eval: func [val /local tmp] [
        either error? set/any 'tmp try [either bind [do system/words/bind load val obj] [do val]] [
            if not quiet [
                tmp: disarm :tmp
                append out reform ["***ERROR" tmp/id "in:" val]
            ]
        ] [
            if not unset? get/any 'tmp [append out :tmp]
        ]
    ]
    parse/all content [
        any [
            end break
            | "<%" [copy value to "%>" 2 skip | copy value to end] (eval value)
            | copy value [to "<%" | to end] (append out value)
        ]
    ]
    out
]

      



Here are some examples of use:

>> x: 1 ;global
>> context [x: 2 print build-markup/bind "a <%x%> b" self]
"a 2 b"
>> print build-markup/bind "a <%x%> b" context [x: 2]
"a 2 b"

      

+1


source







All Articles