在模板文字中使用条件

Ren*_*lla 18 javascript ecmascript-6

我知道有更优雅的方法来定义包含变量的字符串,但如果我想在ES6之前添加条件,我会这样做..

var a = "text"+(conditional?a:b)+" more text"
Run Code Online (Sandbox Code Playgroud)

现在用模板文字我会做..

   let a;
   if(conditional) a = `test${a} more text`;
   else a = `test${b} more text`;
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来实现这种条件?是否可以包含快捷方式?

lil*_*zek 37

用这个:

let a = `test${conditional ? a : b} more text`;
Run Code Online (Sandbox Code Playgroud)


Rem*_*emi 8

您还可以进一步扩展它并在这样的条件中使用占位符。

这实际上取决于您拥有的最易读的用例。

一些例子:

// example 1
const title = 'title 1';
const html1 = `${title ? `<h2>${title}</h2>` : '<h2>nothing 1</h2>'}`

document.getElementById('title-container-1').innerHTML = html1;

// example 2
const title2= 'title 2';
const html2 = `
	${title2 ? 
  	`<h2>${title2}</h2>` : 
  	"<h2>nothing 2</h2>"
  }`

document.getElementById('title-container-2').innerHTML = html2;

// example 3
const object = {
	title: 'title 3'
};

const html3 = `
	${(title => {
      if (title) {
        return `<h2>${title}</h2>`;
      }
	  	return '<h2>Nothing 3</h2>';
		})(object.title)
	  }
`;

document.getElementById('title-container-3').innerHTML = html3;
Run Code Online (Sandbox Code Playgroud)
<div id="title-container-1"></div>
<div id="title-container-2"></div>
<div id="title-container-3"></div>
Run Code Online (Sandbox Code Playgroud)

来源