Gravatar for

Question by DEEPTHI KATTA, Oct 21, 2016 7:26 PM

Access Javascript variable from underscore template in MVC

I am using Coveo for Sitecore with MVC. Say, if i need to access a JS variable from underscore template on MVC view, how do I do this?

Say, I have a var message ="Hello" declared and assigned in my script. I tried combinations like below on underscore and could not get anything to work -

<span>{{= raw['message']}}</span>
<div>Hello:{{- raw.message }}</div>

No errors - But, value comes in as empty, I am pretty sure the variable is declared.

Basically, how can I access JS variable from underscore template on MVC

2 Replies
Gravatar for

Answer by François Lachance-Guillemette, Oct 24, 2016 8:09 AM

The raw variable is bound to each of the results coming from the query. On its first templating, raw will be your first result, then your second result, and so on.

From what I see, the message variable is not bound to any result and is not a field on your documents, meaning it will not be accessible with the raw variable.

You simply need to omit the raw variable altogether to use a Javascript variable in your template.

I just tried out the following code:

var answer = "yes";
< script class="result-template" type="text/underscore">
     <div>Did it work: {{= answer }}</div>
< /script>

And it prints Did it work: yes for each result.

Gravatar for

Answer by ssartell, Oct 24, 2016 9:43 AM

While you can inject server-side variables into your Underscore templates in your Razor files, I wouldn't conflate Underscore templates with MVC. Underscore is a client-side templating tool where MVC is all server-side. That said, I'm assuming the {{- raw.xxxx }} was just a typo and you meant to use an equals sign there. That rest of the syntax should work fine assuming message is actually a property on the raw object of your result.

I'd recommend using your browsers dev tools to figure out what's going on here. Either you can look at the XHR results coming back via the network tab, or you can debug the templates directly to find out what the values you have available are. To do that just drop {{ debugger }} on a line in your template and have your browser dev tools open when you refresh. Then you should be able to figure out what is available to use in your templates.

Gravatar for

Comment by DEEPTHI KATTA, Oct 24, 2016 7:05 PM

Thank you on the comments you guys. I think in my case var message was actually making a server side call to a helper method. Could be that it was not available when rest of HTML was rendered. I will do more experiments.

I did try this:

<div>Did it work: {{= message }}</div>

In my case this causes error for sure. Again, seems like order of processing client vs server side. Let me see if I can do some work around in here

Ask a question