mithril.js icon indicating copy to clipboard operation
mithril.js copied to clipboard

White space in m() strings

Open pelonpelon opened this issue 11 years ago • 4 comments

I find myself creating views with a lot of text. Without resorting to m.trust() or MSX, or multiple m("br") calls, I can't find a way to create spaces and line feeds.

I wonder if it might be a good idea to convert [\n] into <br /> [\ ] into &nbsp; [\t] into &nbsp;&nbsp;&nbsp;&nbsp; within the core? How bad would a regex damage performance? Maybe the regex could be turned on in an attribute?

m("div", {whitespace: true}, "Ash nazg durbatulûk,\n
\ \ ash nazg gimbatul;\n
\ \ ash nazg thrakatulûk\n
\ \ agh burzum-ishi krimpatul")

HTML:

<div>Ash nazg durbatulûk,<br />
&nbsp;&nbsp;ash nazg gimbatul;<br />
&nbsp;&nbsp;ash nazg thrakatulûk<br />
&nbsp;&nbsp;agh burzum-ishi krimpatul.</div>

And appear thus (after Black Speech filter):

One Ring to rule them all,
  One ring to find them;
  One ring to bring them all
  and in the darkness bind them.

pelonpelon avatar May 04 '15 19:05 pelonpelon

This looks like an excellent plugin. Black speech, white space — it's on-brand too ;)

Maybe a use case for custom attributes? #586

barneycarroll avatar May 04 '15 19:05 barneycarroll

I'd much prefer a plugin. "Starve the core!". I look forward to custom attributes. I'd place them as priority #1. I guess I'll just have to enjoy components for the time being. And oh, components are lovely!

BTW: a unicode plugin/attribute, effectively one line of code, sounds like an urgent project considering the Japanese invasion.

pelonpelon avatar May 04 '15 19:05 pelonpelon

A few other options:

//use CSS
m("div[style='white-space:pre']", "a  b\nc\td")

//make a helper function
function sws(str) { //stands for significant white space
  return m.trust(str.replace(/ /g, "&nbsp;").replace(/\n/g, "<br>")).replace(/\t/g, "&nbsp;&nbsp;"))
}

m("div", sws("a  b\nc\td"))

If you only care about HTML entities, you could also just use the respective unicode codepoints

function nbsp(str) {
  return str.replace(/ /g, "\u00A0") //nbsp
}

For japanese, just use unicode:

m.render(document.body, "hello 世界")

lhorie avatar May 04 '15 19:05 lhorie

That's awesome. I never knew about white-space:pre. Sounds like an entry for Common Problems

pelonpelon avatar May 04 '15 23:05 pelonpelon