Using the underscore template to dynamically assign images

Currently, I am utilizing underscore templates to showcase a HTML list demonstrating a series of contact details.

The format of the template is as follows:

<li>
 <span class="name">Name: <=%data.name%></span>
 <span class="email">Email: <=%data.email%></span>
 <img class="avatar" src="<=%data.avatar%>"></img>
</li>

An issue arises when setting the data for the template - the image source remains undetermined. This uncertainty stems from the structure of my data:

contact = {
  name: string, // e.g. 'John Doe'
  email: string, // e.g. '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb6b3b4b29cb8b3b9f2bfb3b1">[email protected]</a>'
  avatar: string // e.g. '11a93150-14d4-11e3'
}

In this scenario, the avatar field does not contain a direct URL but instead a reference to a remote database that necessitates fetching, similar to:

function getAvatar(uuid, cb) { // uuid like 11a93150-14d4-11e3
 window.db.getImageUrl(function(url) {
  cb(url); // url such as http://foo.com/avatar.png
 });
}

The question at hand revolves around whether there exists a method to modify my template so that rather than directly accessing the avatar value within the contact object, I can integrate a call to a function like getAvatar. Consequently, upon rendering the template, the function retrieves the image URL and assigns it to the avatar image element?

Your input is appreciated in advance.

Answer №1

Check out this demonstration showcasing how to invoke JavaScript functions and asynchronously modify the src attribute of thumbnails. The script mimics a database call using setTimeout along with an associative array as the database.

Sample HTML:

<script type='text/html' id='contactTemplate'>
    <li id="contact-<%= avatar %>"> 
     <span class = "name"> Name: <%= name %> </span>
     <span class="email">Name: <%= email %></span> 
     <img class = "avatar" data-populate-path="<% getPath( avatar ) %>" />
    </li>
</script>
<ul id='contactList'></ul>

JavaScript code:

var contacts = [
    {name: 'John Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84eeebeceac4e0ebe1aae7ebe9">[email protected]</a>', avatar: '11a93150-14d4-11e3'}, 
    {name: 'Hannah Smith', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cfc6c9c9c6cfe7d4caced3cf89c4c8ca">[email protected]</a>', avatar: '11a93150-14d4-1231' }
],

simulatedDB = [];
simulatedDB['11a93150-14d4-11e3'] = "path to avatar 1";
simulatedDB['11a93150-14d4-1231'] = "path to avatar 2";

$(document).ready(function () {
    var compiled = _.template($("#contactTemplate ").html());

    _.each(contacts, function (d, i) {
        $("#contactList").append(compiled(d));
    });
});
function getPath(target) {
    setTimeout(updateAvatar, 1000, target);
}
function updateAvatar(target) {
    $("#contact-"+target+" img").attr("src", simulatedDB[target]);
}

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

Loading a new view within AngularJS using the ng-view directive opens up a fresh

I am currently working on integrating Angular with a REST API for the login process. After successfully setting up Angular with my REST calls, I aim to redirect to a new page upon successful login. In my success handler, I have implemented the following ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

React - retrieving the previous page's path after clicking the browser's "back" button

Imagine I'm on Page X(/path-x) and then navigate to page Y(/path-y). Later, when I click the "back" button in the browser. So my question is, how do I retrieve the value of /path-y in PageX.tsx? Note: I am utilizing react-router-dom ...

What is the simplest way to test an npm module while coding?

Currently, I am in the process of making modifications to @editorjs/nested-list. To streamline my testing process without extensive installations, I have created a simple web page: <html> <head> <script src="https://cdn.jsdelivr.net/npm ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Trouble with cookies in CakePHP during an AJAX request?

Currently, I am working on implementing an Ajax login feature using the auth component within my CakePHP application. Everything seems to be functioning correctly except for the "remember me" functionality. I have been attempting to set a cookie using the ...

"Exploring the concept of object occlusion with transparent elements in

Is it possible to create an object in a three.js scene that is invisible but still acts as if it's blocking other objects? For example, say we have objects a, b, and c in the scene along with a camera. I want object c to be unseen by the camera, yet s ...

Show a Google map when hovering over a link or text

I have been trying to implement a Google map display over text by following a tutorial. However, I've encountered an issue where the map is appearing in the wrong location – at the bottom of the page instead of where it should be. Upon inspecting th ...

Submitting a jQuery variable via AJAX to an external PHP SQL script and receiving results

I'm attempting to pass a jQuery variable called dataString, which is a string, via ajax to an external file drug_scripts.php that will display the value. When I pass a numerical value as the data, it works fine. However, when I try to pass the variabl ...

Transferring data files through an ajax-based form submission

I am encountering an issue when trying to send a file to a server using AJAX for submission. Despite attempting various methods involving var xhr = new XMLHttpRequest(); and $.ajax({});, I consistently receive the error message Uncaught TypeError: Illegal ...

Implementing Datatrans Ajax in Wordpress is a seamless process that enhances

I'm in the process of integrating a credit card payment service from datatrans.ch into my WordPress site. Datatrans provides an Ajax API, which you can access here: Datatrans Ajax API Example Code I copied and pasted the example code, saved it in a ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

The Puppeteer has obliterated the Execution Context

"Likely attributed to page navigation" The issue I'm encountering with the page in question stems from its navigation process. In order to access the desired content, I must click a specific button. However, upon clicking said button, the c ...

Filter products by price using Ajax in Shopify with Liquid code

I am looking to implement a custom product price filtering feature for my collection without relying on an app. Unlike the traditional price filter option, I want users to be able to input any combination of numbers, such as between $4 and $20 or $7 and $3 ...

Unable to retrieve all the necessary data from the LinkedIn API

I have attempted the following: Code Snippet in HTML: <a id="li_ui_li_gen_1432549871566_0-link" class="" href="javascript:void(0);" onclick="onLinkedInLoad();" style="margin-bottom: 20px;"> Javascript Function: function onLinkedInLoad(logintype) ...

Failed to fetch http://localhost:8000/Stack/script.js due to network error 404 in Django project

As I embark on creating a simple to-do app, I encountered an error while trying to implement some JavaScript on the homepage. The error in question is highlighted above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404). Being new to integra ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...

Is it feasible to utilize jQuery mobile without the use of AJAX, relying only on styles?

While I am aware of the jQuery Mobile download-customizer, I am struggling to determine which options need to be selected. It appears that the styles for input elements are somehow connected to the AJAX functionality? All I really desire is to have stylis ...

What are the HTML5 elements that include the "load event" within their onload attribute?

Mozilla's MDN provides information regarding the load Event with this brief explanation: The load event is triggered when a resource and its dependent resources have completed loading. and references standard 1, which states Trusted Targets: ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...