Stop underscore templates from accessing global variables

I have a question about my underscore template. Here is the section of code in question:

<% if (typeof title !== "undefined") { %>
    <p class="title"><%= title %></p>
<% } %> 

Is there a way to avoid using the global scope when rendering this template without name spacing the data? I am unable to safely remove title from the global scope as it is not my own code and requires reliance on undefined. Any suggestions would be greatly appreciated.

Answer №1

ahem ahem my patch, scans template for keys and generates placeholders

https://github.com/jashkenas/underscore/issues/237

if you're hesitant to modify a core library with code from the web :)

you could enclose the template in a try-catch block to display an error message

<% try { %>
    TEMPLATE OF DOOM FULL OF FAIL
<% } catch (error instanceof ReferenceError){ %> 
    GENERIC REFERENCE ERROR MESSAGE
<% } %>

alternatively, pass in an object wrapper, and access the wrapped key

for example, observe how "dataIWasGoingToPutIntoTemplateUnwrapped" is encapsulated within the key "data"

var dataIWasGoingToPutIntoTemplateUnwrapped = {
     iAmVar: "hello",
     iHasVarKThxBye: "world"
};

var underscoreTemplate = _.("<%= data.iAmVar %> and <%=data.iHasVarKThxBye%>");
console.log(underscoreTemplate({data:dataIWasGoingToPutIntoTemplateUnwrapped }));

Answer №2

Unfortunately, the answer is a resounding no (special thanks to Bergi for their input). Despite my efforts to avoid it, I ultimately had to tackle the task of updating numerous intricate underscore templates from <%= foo %> to <%= data.foo %>.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on obtaining the element that was used as the event selector

I am facing a challenge with a specific issue. Within a div containing various elements, I have implemented a mouseover event. The issue arises when trying to target this particular div in the mouseover function, as there are multiple automatically genera ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

Unable to render backend-sourced images in ReactJS

I'm currently working on a project that involves displaying images fetched from the backend. I've been successful in displaying all the data except for the images. Below is the response I received when I logged the response: [ { "_id&qu ...

What is the significance of employing the `var` keyword in Vue.js?

As I dive into tutorials and browse through code snippets while immersing myself in learning this framework, I've noticed a common trend - the use of var for declarations. This practice seems prevalent across resources, including the official Vue docu ...

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

The jQuery hide and show functions lack precision and are too indiscriminate, requiring a more targeted approach

I am designing a unique contact card that captures a user's name and description from an <input> field and appends the input information into a <div> element. This is the flow I am aiming for... User inputs their first and last name alo ...

Interactive elements embedded within an image - digital board game

I'm currently working on integrating a board game into React, and I am facing some difficulties in figuring out how to translate the board squares shown in the image into data. Is there a method through which I can assign unique IDs to each square di ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...

Problems with the navigation bar scrolling in Bootstrap

The project I'm currently working on is located at zarwanhashem.com If you'd like to see my previous question along with the code, you can check it out here: Bootstrap one page website theme formatting problems Although the selected answer help ...

Determining the local coordinate system of an object in THREE.js

I'm a beginner in Three.js and could use some guidance... I've been moving and rotating an object randomly multiple times. Eventually, I need to determine the orientation of the local coordinate system of that object for physics calculations... ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

JavaScript - Issues with Cookie Setting

I created a function for setting cookies: function storeCookie(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (1000*60*60*24*exdays)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...