How to use the SafeString function from handlebars

Find comprehensive JavaScript handlebars.SafeString code examples handpicked from public code repositorys.

handlebars.SafeString is a function that wraps a string in a SafeString object that will not be escaped by Handlebars during rendering.

639
640
641
642
643
644
645
646
647
648
649
function homepageBuilder(page, completion, redirect) {
	var indexInfo = generateHtmlAndMetadataForFile(postsRoot + 'index.md');
	var footnoteIndex = 0;


	Handlebars.registerHelper('formatDate', function (date) {
		return new Handlebars.SafeString(new Date(date).format('{Weekday}<br />{d}<br />{Month}<br />{yyyy}'));
	});
	Handlebars.registerHelper('dateLink', function (date) {
		var parsedDate = new Date(date);
		return '/' + parsedDate.format("{yyyy}") + '/' + parsedDate.format("{M}") + '/' + parsedDate.format('{d}') + '/';
fork icon55
star icon265
watch icon27

+ 8 other calls in file

98
99
100
101
102
103
104
105
106
107


  profileAvailCheck: (avail, options) => {
    if(avail === true) {
      return new SafeString('<p class="w-[33%] text-center text-green-800">Working</p>')
    } else {
      return new SafeString('<p class="w-[33%] text-center text-red-800">Not Working</p>')
    }
  }
}
fork icon0
star icon3
watch icon0

+ 3 other calls in file

How does handlebars.SafeString work?

handlebars.SafeString works by taking a single input, which is a string that should be marked as safe for rendering.

The function returns a new SafeString object that wraps the input string.

When the SafeString object is rendered by Handlebars, the contents of the string will not be escaped or modified in any way.

By using handlebars.SafeString, you can mark a string as safe for rendering by Handlebars, which can be useful when working with templates that contain HTML, CSS, or other content that should not be modified during rendering.

394
395
396
397
398
399
400
401
402
    let translated = gt.gettext(args[0]);
    if (params.length) {
        translated = util.format(translated, ...params);
    }

    return new handlebars.SafeString(translated);
});

handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
fork icon113
star icon0
watch icon16

23
24
25
26
27
28
29
30
31
32
  return true;
}

setupHandlebars() {
  Handlebars.registerHelper("renderMemberName", function() {
    return new Handlebars.SafeString(/^[A-Za-z0-9]*$/.test(this.memberName) ? this.memberName : `'${this.memberName}'`);
  });
}

async renderIndex(data) {
fork icon4
star icon0
watch icon8

+ 13 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const Handlebars = require("handlebars");

// Create a string that contains HTML content
const htmlContent = " Hello, world! ";

// Wrap the string in a SafeString object
const safeHtmlContent = new Handlebars.SafeString(htmlContent);

// Render a Handlebars template that includes the HTML content
const template = Handlebars.compile("{{content}}");
const renderedTemplate = template({ content: safeHtmlContent });

console.log(renderedTemplate); // Hello, world!

In this example, we use handlebars.SafeString to mark a string containing HTML content as safe for rendering. We first create a string htmlContent that contains a paragraph element with the text "Hello, world!". We then wrap htmlContent in a SafeString object using new Handlebars.SafeString. We compile a Handlebars template that includes the content variable, and then pass an object with the content property set to safeHtmlContent to the template using the template function. Finally, we log the rendered template to the console. The resulting output demonstrates how handlebars.SafeString can be used to mark a string as safe for rendering by Handlebars.

170
171
172
173
174
175
176
177
178
179
180
};


exports.mylink = function(object, options) {
	if (object.link) {
		var link = exports.tolink(object.link);
		return new Handlebars.SafeString(
			"["+options.fn(object)+"]("+link+")");
	}
	return options.fn(object);
};
fork icon3
star icon4
watch icon1

+ 47 other calls in file

94
95
96
97
98
99
100
101
102
103
104
105
    }


    queryStringSnippet += newLine + serialisedQueryParam;
  }


  return new Handlebars.SafeString(queryStringSnippet);
};


module.exports = createQueryStringSnippet;
fork icon0
star icon1
watch icon14

+ 4 other calls in file

34
35
36
37
38
39
40
41
42
43
44
    enums.forEach((e) => {
      html += `<li>${String(e)}</li>`;
    });
  }
  html += "</ul>";
  return new Handlebars.SafeString(html);
});


Handlebars.registerHelper("isDefined", function (value) {
  return value !== undefined;
fork icon3
star icon6
watch icon2

+ 2 other calls in file

311
312
313
314
315
316
317
318
319
320
chapterText: (str) => {
    str = str.toString().replace(/-/g, ' ').replace("apter", '. ');
    return str && str[0].toUpperCase() + str.slice(1);
},
encodeMyString: (text) => { 
    return new Handlebars.SafeString(text);
}
,
breakWords: (str) => {
    var words = str.trim().split(' ')
fork icon1
star icon0
watch icon0

+ 2 other calls in file

50
51
52
53
54
55
56
57
58
59
 Handlebars.registerHelper('commalist', function(items, options) {
   return options.fn(items.join(', '));
});

// Handlebars.registerHelper('formatdate', function(text) {
// 	return new Handlebars.SafeString(text.slice(0,7));
// });

Handlebars.registerHelper('breaklines', function(text) {
	text = Handlebars.Utils.escapeExpression(text);
fork icon1
star icon0
watch icon0

92
93
94
95
96
97
98
99
100
101
app.use(bodyparser.json())
//handlebars
app.engine('handlebars', handlebars.engine({defaultLayout: 'main'}))
app.set('view engine', 'handlebars')
Handlebars.registerHelper('error_', function (message) {
    return new Handlebars.SafeString(`<div class="error">${message}</div>`);
  });
Handlebars.registerHelper('ifCond', function(v1, operator, v2, options) {
    switch (operator) {
      case '==':
fork icon0
star icon0
watch icon1

+ 2 other calls in file

55
56
57
58
59
60
61
62
63
64
65
    },
    'helperMissing': function() {
        /** @type {Handlebars.HelperOptions} */
        const options = arguments[arguments.length - 1]
        const args = Array.prototype.slice.call(arguments, 0, arguments.length - 1)
        return new Handlebars.SafeString("Missing: " + options.name + "(" + args + ")")
    }
}


class WebInterfaceManager {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

68
69
70
71
72
73
74
75
76
77
78
79
80


            translation = textToTransform;
        }
    }


    return new Handlebars.SafeString(translation);
}


/**
 * Helper function to return a value inside the object for a given object path
fork icon0
star icon0
watch icon1

+ 5 other calls in file

23
24
25
26
27
28
29
30
31
32
   var localization 	= require('utils/LangSupport');
require('moment');
/*
 * General guidelines while writing helpers:
 * 
 * - If returning HTML use return new Handlebars.SafeString();
 * - If the helper needs optional arguments use the "hash arguments"
 *   Eg. {{{link . "See more..." story.url class="story"}}}
 *   NOTE: the first argument after the helper name should be . which will be context in the helper function
 *   Handlebars.registerHelper('link', function(context, text, url, options) {
fork icon0
star icon0
watch icon1

+ 59 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26


	let output = `<svg ${attributes}>
		<use href="${iconId}">
	</svg>`


  return new Handlebars.SafeString(output)
}


module.exports = icon
fork icon0
star icon0
watch icon0

21
22
23
24
25
26
27
28
29
30
31


        const address = Handlebars.escapeExpression(`?_sort&column=${field}&type=${type}`)


        const output = `<a href="${address}"><i class="${icon}"></i>    </a>`;


        return new Handlebars.SafeString(output);
    }
}
fork icon0
star icon0
watch icon0

41
42
43
44
45
46
47
48
49
50
51
    // Will need to put the output path as a root on this URL, which is partialy defined in
    // config file - Can I pass that in??
    // Also - Will need to make sure all output files (images, css, script) are pushed to the output dirs
    // _before_ the rest of the HTML template processing, so this helper can find the file content to
    // hash in the right directory.
    return new Handlebars.SafeString(ret + sepChar + Files.getMd5ForFile(ret))
})


/** Main Entry Point */
const handler = async (event, context) => {
fork icon0
star icon0
watch icon0

+ 2 other calls in file

21
22
23
24
25
26
27
28
29
30
app.use(i18n.init);
app.engine('hbs', exphbs({
    extname: '.hbs',
    defaultLayout: 'main',
    helpers: {
        i18n: (s, req) => new Handlebars.SafeString(req.data.root.__(s))
    }
}));
app.set('view engine', 'hbs');

fork icon0
star icon0
watch icon0