Is invalid HTML causing issues with Backbone.js templating in Phonegap?

Summary: When my template file contains valid HTML code, it does not display in Phonegap.

The structure of my index.html file is as follows:

<body onload="onBodyLoad()">
    <div data-role="page">
      <a href="#login" id="clickme">Click to go to Login</a>
    </div>
  </body>

As for my template file, it is currently quite simple:

<div data-role='content' id='loginpage'>
this is a test
</div>

The issue arises when I attempt to display the template using the following Backbone code:

var LoginPage = Backbone.View.extend({
    initialize: function(){
      this.template = _.template(tpl.get("login"));
      console.log("Got Login Template");
      console.log(this.template);
    },

    render: function(e){
        console.log("rendering login page with the following user");
        console.log(this.model);
        $(this.el).html(this.template(this.model));
        this.mainView = new LoginView({ el: $("#loginpage", this.el), model: this.model });
        this.mainView.render();
        return this;
    }
});

var LoginView = Backbone.View.extend({

    initialize: function(){
    },

    render: function(e){
        console.log("rendering login view");
        return this;
    }
});

Unfortunately, it doesn't work as expected.

An interesting observation is that adding an invalid tag (such as a lone opening or closing tag) to the template file allows it to display perfectly. It could be a closing div, an opening table, an opening label, a closing p, etc. Any invalid tag seems to make it work.

So, what's going on?
It should be noted that both scenarios work fine in Chrome.

EDIT

The problem seems to be related to the functionality of tpl. The error appears to occur within this section of the code. If the HTML is valid, it fails to load.

tpl = {

    // Hash of preloaded templates for the app
    templates: {},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    loadTemplates: function (names, callback) {
        var that = this;

        var loadTemplate = function (index) {
            var name = names[index];
            console.log("Loading " + name);

            $.ajax({
                url: 'templates/' + name + '.html',
                data: {},
                success: function (data){
                    that.templates[name] = data;
                    index++;
                    if (index < names.length) {
                        loadTemplate(index);
                    } else {
                        callback();
                    }
                },
                error: function (msg) {
                    console.log(msg);
                },
                async: false
            });
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        console.log('getting ' + name);
        var temp = this.templates[name];
        console.log('got it!');
        return temp;
    }

};

Answer №1

I encountered a similar issue with backbone template when testing it on a device. I managed to resolve the issue by modifying the loadTemplate method as shown below:

var loadTemplate = function (index) {
            var name = names[index];
            console.log('Retrieving template: ' + name);

            var data = $.ajax({type: 'GET', url: 'tpl/' + name + '.html', async: false}).responseText;
            that.templates[name] = data;
            index++;
            if (index < names.length) {
                loadTemplate(index);
            } else {
                callback();
            }
        }

Answer №2

James.

<div data-role='content' id='loginpage'>
this is just a sample 
</div>

My apologies, is this the actual template being used for the LoginPage view? It seems like you are passing a model as a parameter to the template method, which might be causing confusion. I believe the issue lies in this line of code. Please try changing from

$(this.el).html(this.template(this.model));
to
$(this.el).html(this.template(this.model.toJSON()));

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

Implementing a DataTable filter functionality using external buttons or links

I want to enhance the search functionality of my table by incorporating a treeview style set of buttons or links next to it. This is how I envision it: Take a look at this design: https://i.sstatic.net/LAJXf.png Here's where it gets tricky. When I c ...

Header stabilization on scroll

On my webpage, I have a table header positioned in the middle of the page. However, due to the length of the page, I am looking for a way to make the header stay fixed at the top of the browser as the user scrolls down. My query is: Is there a method to k ...

Error: The specified module is missing an export that was requested

Hello, I encountered an error in my console that reads: "Uncaught SyntaxError: The requested module './components/tileHeader/controller.js' does not provide an export named 'tileHeader'". Below is the code snippet causing the issue: co ...

Creating a Dynamic Login Panel Using HTML, CSS, and Jquery

Designing a dynamic sliding login panel utilizing Html, CSS, and jquery alongside various plugins. Check it out here: http://24.125.42.135/ When activated, the bar smoothly pushes down the content (click on the login option at the top right corner). This ...

Guidelines for sorting through items in Vue 3

In the past, Vue 2 allowed us to easily filter items using the | and filters syntax. However, this method is no longer supported in Vue 3. Instead, we now use the "computed" property to transform a single value into another. But what about changing values ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

"Transitioning from jQuery to Vanilla Javascript: Mastering Scroll Animations

I'm seeking guidance on how to convert this jQuery code into pure Javascript. $('.revealedBox').each(function() { if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) { $(this).addCla ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

Looking to improve query performance on MongoDB using mongoskin - should you use a single query or

this relates to mongodb {cod_com:'WWWOAN', cod_prod[{prod:'proda',info:'hello world'},{prod:'pacda',info:'hello world'},{prod:'prcdb',info:'hello world'}] } {cod_com:'WWWOA2&a ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

Using JQuery to retrieve part of a className results in a null value being returned

I am facing an issue with a piece of code in codesandbox where it returns null when I attempt to retrieve part of the className from a div using JQuery. How can I troubleshoot this and make it work? Check out the Codesandbox Example import React, { Compo ...

Stop the slideshow when hovering

I have successfully implemented a script for running a slideshow. The script works well and does the job perfectly. jQuery(document).ready(function ($) { setInterval(function () { moveRight(); }, 5000); var slideCount = $('#slider ul li' ...

Does IE 9 support endless local storage capacity?

I recently updated my HTML5 persistent storage (localStorage) capacity testing to address a memory exception issue in the previous version. I even created a jsFiddle showcasing it: http://jsfiddle.net/rxTkZ/4/ The testing code involves a loop: var val ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

jQuery and ajax method are failing to insert data into the database

I am having trouble inserting data into the database using jQuery and Ajax. Can someone please assist me in figuring out if I'm doing something wrong? Here is the code snippet: form.html <!DOCTYPE html> <html> <head> & ...

Scroll automatically to the following div after a brief break

On my website, the title of each page fills the entire screen before the content appears when you scroll down. I am interested in adding a smooth automatic scroll feature that will transition to the next section after about half a second on the initial "ti ...

Creating a SAS URL for Azure Blob storage in Node.js using the generateBlobSASQueryParameters method from the @azure/storage-blob module

Hello, I am working with an Azure storage account where I upload and create a SAS URL to download images. Below is the code snippet that I have used: const { BlobServiceClient, StorageSharedKeyCredential, BlobSASPermissions, generateBlobSASQueryPar ...

Utilizing Nginx to Reverse Proxy to Node.js and Implement Rewrites

I have various applications running in the background behind an Nginx reverse proxy. One of these applications is a Node server using Express.js. I am forwarding domain.com/demo/app/<path> to localhost:7003/<path> through this Nginx configurati ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

The issue with mocking collections using JSON files in Backbone is that it is not properly triggering the success callbacks in

For my project, I am exploring the use of .json files to mock GET requests in a backbone collection. Here is an example of my sample file: [ { "id": '11111', "name": "Abdominal Discomfort", "favori ...