TeslaXba
TeslaXba

Reputation: 357

How to use velocity variable in JavaScript?

I am trying to use a variable from velocity in my external js file. I had a look also at Access Velocity Variable in JavaScript File but that helped me only use it in js only if it is written in the .vm file.

My velocity:

 #set ($testvar= "#include('templates/some.txt')")
 <script type="text/javascript">
    #include("templates/currencyDetail.js")
    var myvar = "${testvar}";    
    </script>

    <body>
        <div class="myConfluenceMacro">
            <fieldset class="parameters hidden">
                <input type="hidden" class="dayDates" value= myvar>
            </fieldset>
        </div>
    </body>

MY JS:

 $(document).ready(function(){
        $(".myConfluenceMacro").each(function(){

            var dayDates = $(this).find("input.dayDates").val();

            $(this).html("Hello <b>world!</b>" + dayDates );
        });
    });

When I print it out, I get only

$!{testvar}

as output, but not the value of my value... Does it have to be a json or can I send a string that I have read from the .txt file?

Thank you!

Upvotes: 1

Views: 4270

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

What you can do is to set your velocity variable directly as a value of your input, using value="$testvar".

This is how should be your template code:

#set ($testvar= "#include('templates/some.txt')")
<body>
    <div class="myConfluenceMacro">
        <fieldset class="parameters hidden">
            <input type="hidden" class="dayDates" value="$testvar">
        </fieldset>
    </div>
</body>

In your JS:

$(document).ready(function(){
        var dayDates = $("input.dayDates")[0].value;
        $(this).html("Hello <b>world!</b> " + dayDates );
});

You can take a look at Velocity Reference Miscellany docs for further details.

Upvotes: 1

Related Questions