Rebol Tutorial
Rebol Tutorial

Reputation: 2754

Rebol: How to use local variables with build-markup function?

Is there a way to do so including creating an other build-markup function ?

Upvotes: 2

Views: 261

Answers (2)

endo64
endo64

Reputation: 2307

I've patched the build-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 example usages:

>> 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"

Upvotes: 1

Sunanda
Sunanda

Reputation: 1555

Sadly,build-markup uses only global variables: link text says: Note that variables used within tags are always global variables.

Here's a slightly cranky way of doing it using an inner object (bm-1 demonstrates the problem: a and b are printed with their global values; bm-2 is the cranky work around):

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 reword rather than build-markup. That is much more flexible.

Upvotes: 1

Related Questions