utilize a function to format text in dust.js style

I have created a JavaScript function that blurs text:

function blurText(data) {
    var dataSplit = data.split(" ");
    var lastWord = dataSplit.pop();
    var toBlur = '<span class="blur">' + dataSplit.join(" ") +  '</span>'; 
     var output = '<li>' + toBlur + lastWord + '</li>';
     return output;
}

I am attempting to use this function with dust.js by doing something like:

{#storylines}
    <script>
        blurText("{text}");
    </script>                   
{/storylines}

Is there a simple way to pass the {text} value through a JavaScript function and then display the output?

When I run it in the console, it appears to be working correctly:

> blurText("This is a test line")

> "<li><span class="blur">This is a test</span>line</li>"

Answer №1

In my coding practice, I often create a utility function within the global scope:

var blurText = dust.makeBase({
    blurText: function(chunk, context, bodies, params) { 
        var dataSplit = params.data.split(" ");
        var lastWord = dataSplit.pop();
        var toBlur = '<span class="blur">' + dataSplit.join(" ") +  '</span>'; 
        var output = '<li>' + toBlur + lastWord + '</li>';
        return chunk.write(output);
    }
});

To incorporate it into the local context during rendering:

dust.render("template", dustCtx.push({storylines:...}), function(err, out) {});

Then use it like this:

{#storylines}
    {#blurText data=text/}
{/storylines}

This method may be useful for passing additional parameters, such as controlling the blurring effect.

Answer №2

To make it functional, I devised a dust.js filter.

  bl: function(value){  var dataSplit = value.split(" ");
    var lastWord = dataSplit.pop();
    var toBlur = '<span class="blur">' + dataSplit.join(" ") +  '</span>'; 
     var output = toBlur + lastWord;
     return output; }

In the template, I am inputting the following:

{#storylines}
    <li>{text|bl|s}</li>    
{/storylines}

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

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Getting the PSID of a Facebook bot during the process of Account Linking

Hey there, I'm in need of some guidance on how to obtain the Page Scope ID (PSID) or Sender ID during the Account Linking process. I've looked at the documentation and it suggests using the following solution. However, I'm not sure how to i ...

Accessing a terminal interface for Linux or Windows via the internet

I have an idea for a web application that will host a Linux Terminal directly on a webpage, allowing users to run commands and receive responses as if they were using their own Linux terminal. My initial plan is to utilize NodeJS due to its server-side Jav ...

Facing issues with Google token authentication using Express and Passport

Recently, I created a REST api utilizing Express with Passport and the passport-google-token strategy for user authentication. Surprisingly, everything functions flawlessly when the server is running on localhost, but encounters issues on the live version ...

What is the best method for updating audio from a source in Vue.js?

Forgive me if this is a silly question, but I'm still learning the ropes here. I may be going about this in all the wrong ways! I created a backend that learns from a text file and generates sentences along with an audio version of those sentences. I ...

Angular deep linking in an Express server is a powerful combination that allows

I'm developing a single page application using Express and Angular. One feature involves sending users an email with a link to reset their password (https://[domain].com/reset-password/[token]). However, when the user clicks on this link, it redirect ...

Data not populating correctly in MEAN Stack application

Currently grappling with the challenge of making this web app operational using the MEAN Stack, I find myself at a standstill. The root cause is unclear to me. Upon refreshing my page and commencing data entry by filling out all fields before clicking on " ...

Having trouble generating package.json with npm init on my Mac

Every time I attempt to generate a package.json file by using the command npm init, I encounter the following issue: npm http GET https://registry.npmjs.org/init npm http 304 https://registry.npmjs.org/init npm http GET https://registry.npmjs.org/daemon n ...

Ways to incorporate JSON web token into every query string of my requests

Just recently, I grasped the concept of using JSON web tokens. Successfully, I can generate a JSON web token upon sign-in and have also established the middleware to authenticate my token and secure the routes that fall under the JSON verification middlewa ...

Troubleshooting a Heroku build failure in Node.js due to issues with the Mongodb module

While deploying my app on Heroku, I am facing an issue. My app uses Express and Mongodb. Even though the repository works fine during local development, when deployed on Heroku, there is an error in the logs related to the Mongodb module itself. How can I ...

Is there a comparable option to Jades extend in the world of Handlebars?

Considering transitioning the templating language of my express app from Jade to Handlebars. I am curious if there exists a similar directive in Handlebars as the Jade extend directive. ...

What steps should I take to program my bot to identify a specific reaction and automatically send a message in response?

Currently, I'm working on implementing a help command that utilizes reactions. The idea is that the bot will add a reaction, prompting the user to react, and once they do, the corresponding help message will be displayed. However, I've hit a road ...

There seems to be an issue with the connection between socket.io and the server

Recently, I encountered an issue while hosting my application on OpenShift with a custom domain. The problem arose when socket.io failed to download the client-side script, leading me to resort to using a CDN instead. However, this workaround has caused an ...

Utilizing Node.js: Chaining process.exit() functions

Is there a way to chain process.on('exit') calls in JavaScript? process.on('exit', function firstHandler(err,code,cb){ //this signature is fictitious for this example only if(condition){ cb(null); // this would call the ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'you ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

NodeJS Express Double Authentication using JSON Web Tokens

Currently, I am in the process of developing an express server that enables users to authenticate using two third-party services: Google and Steam. The authentication is accomplished through JWT and functions well when only one service is active. However, ...

Aggregating data with multiple arguments in MongoDB is a powerful

I'm attempting to retrieve multiple arguments from my MongoDB database. Currently, my code fetches the distinct values for dates and counts them. However, I am unsure how to include another argument to fetch a different set of distinct values and coun ...

Increment field(s) conditionally while also performing an upsert operation in MongoDB

I need to perform an insert/update operation (upsert) on a document. In the snippet below, there is a syntactical error, but this is what I am attempting to achieve: $inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1}, If the ...

Sending numerous files from a Google Cloud virtual machine to Google Cloud Storage through node.js and a library called Glob

Exploring the use of Node.js for uploading multiple files from my Google Compute Engine VM local directory to a pre-existing GCS bucket has hit a snag. With each script execution, I encounter the following error message: TypeError [ERR_INVALID_ARG_TYPE]: ...