Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable inside a CDATA block, in Javascript?

CDATA-blocks work great for coding large blocks of HTML, or CSS, into strings. But, I can't figure out how to use a variable-value within one.

For example, consider this JavaScript code:

var FullName    = "Friedrich Hayek";
var ProfileCode = (<><![CDATA[
                    <div id="BigHonkingChunkO_HTML">
                        ...Lot's o' code...

                        Name: $FullName$
                        Birth: $Birthdate$

                        ...Lot's o' code...

                        ... $FullName$ ...

                        ...Lot's o' code...
                    </div>
                ]]></>).toString ();


How do I get $FullName$ to render as "Friedrich Hayek" instead of "$FullName$"?

Note that there is more than one variable and each variable can be used a few times in the CDATA block.


Alternate code sample:

var UserColorPref   = "red";
var UI_CSS          = (<><![CDATA[
                        body {
                            color:              $UserColorPref$;
                        }
                    ]]></>).toString ();

Looking to set the color attribute to red.

like image 971
Brock Adams Avatar asked Dec 02 '25 08:12

Brock Adams


1 Answers

Is it elegant enough ?

function replaceVars(content, vars)
{
    return content.replace(/\$(\w+)\$/g, function($0, $1)
    {
        return ($1 in vars ? vars[$1] : $0);
    });
}

ProfileCode = replaceVars(ProfileCode, {"FullName" : "Friedrich Hayek"});

In case associative keys don't really matter, you can always opt to use:
sprintf or vsprintf

EDIT

What about making the 2nd parameter optional ?

function replaceVars(content, scope) {
    if (!scope || typeof scope != "object") {
        scope = this;
    }

    return content.replace(/\$(\w+)\$/g, function($0, $1) {
        return ($1 in scope ? scope[$1] : $0);
    });
}

// example1
var FullName = "Friedrich Hayek";
ProfileCode = replaceVars(ProfileCode);

// example2
var vars = {"FullName" : "Friedrich Hayek"};
ProfileCode = replaceVars(ProfileCode, vars);
like image 169
w35l3y Avatar answered Dec 03 '25 22:12

w35l3y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!