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

"Enhancing the Today Button in FullCalendar with Custom Functionality

My issue lies with the implementation of fullCalendar. Specifically, I am utilizing the week view (defaultView: 'basicWeek') with the toolbar buttons for 'today', 'prev', and 'next'. The problem arises when I click t ...

Using Ajax to Receive Data in a Separate JavaScript Function

I have a scenario where I am making an AJAX call in one function and attempting to capture the result in another function. Let me explain this in detail below: function myMain(){ var test = myWPackage(); alert(test); } function myWPackage(){ ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...

What is the best way to combine multiple periods into a single range?

I am on a quest to find a way to transform sound frequency into light frequency, essentially turning sound into color. Currently, I have managed to come up with a straightforward formula that converts the sound frequency into the light frequency range: co ...

Does the Width Toggle Animation fail to function in FireFox when using jQuery?

Has anyone else encountered this issue with the jQuery animate function not working in Firefox but working fine in IE8, Opera, and Chrome? I'm experiencing this problem and wondering if there's a workaround to make it work in Firefox as well. ht ...

Using jQuery functions on inputs within a Bootstrap Modal

I've encountered an issue with my jQuery functions that validate input fields based on a regex pattern. Everything works smoothly when the form is displayed on a regular page, but as soon as I try to implement it within a Bootstrap Modal, the validati ...

When attempting to render a React child, it is important to note that objects are not valid (found: [object Promise]). If your intention was to display a collection of children, it is advised

Instructions in "/pages/blog/index.js" : import BlogComponents from "../../components/Blog/blogComponents"; import { listBlogs } from "../../server/mongodb"; const index = async (props) => { console.log(props) return ( ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

Utilize a date state variable in JSX Text based on a specific condition

My goal is to create a feature that allows users to pick a date using DateTimePickerModal. I want to display a clickable message that says "Select date" before any date is chosen, and then replace it with the selected date. While I am not certain if there ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet: function add_cnh(arr_clelem){ var id=arr_clelem.getElementsByClassName("present")[0].id; var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date'); v ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

What is the best way to adjust the decimal values in my API calls?

Is there a way to adjust the numerical data returned by the API to display only two decimal places instead of three? For example, if the number is 140.444, I want it to show as 140.44 What changes do I need to make? function fetchData() { fetch(" ...