简体   繁体   中英

get data from express-handlebars to my javascript file

I am using node and express, for template engine I am utilizing express-handlebars. In my handlebars template file I have the following code for displaying a chat user's name:

  <!-- CHAT ROOM -->
    <div class="panel-heading">
      CHAT ROOM
      <span class="pull-right" id="chatbox-username">
        {{#if user}}
        {{user.name}}
        {{/if}}
      </span>
    </div>

This gets the currently logged in user's name and displays it in the chatbox when the user types in their message. The following portion of the script is where I set the username and id variables in my js file to display the username:

var username = $("#chatbox-username").val();
username = '{{ user.name }}';
var userId = '{{ user.name }}';

as you can see I am using express handlebars notation inside single quotes to assign the value to the javascript variable username and userId.

The Problem

I have taken the script out from the bottom of the handlebars file and placed it separately in it's own js file. by using the script tag I now call the file into the handlebars template.

<script src="/rtc/rtc.js"></script>

Since my handlebars and js files are separate now, I am unable to pass the value to the variable as I was doing before.

What should I do to get it working again?

OK...got it working. Simply created a hidden text input with an id

<input type="text" value="{{user.name}}" id="my-name" hidden>

and used:

var userId = $("#my-name").val();

to assign the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM