ES6 之 04.模板(標籤)字符串

索引

模板字符串
const person='Jelly';
const age=20;

const  intro=`${person} is ${age} years old`;

const html=`
 <div class="greet">
    <p>hello</p>
 </div>
`.trim()
const Jelly={
    name:'Jelly',
    date:'2020-02-10',
    todos:[
        {name:'sleep in bed',completed:false},
        {name:'music',completed:true},
        {name:'water',completed:false}
    ]
}

function renderTodos(todos) {
    const str=
        `<ul>
            ${todos.map(todo =>
            `
             <li>
              ${todo.name} ${todo.completed ? '1' : '0'}
             </li>
            `).join('')
            }
          </ul>
        `
    return (str)

}
const tpl=`
<div class="panel">
  <div class="panel-header">${Jelly.name}</div>
  <div class="panel-body">
    ${renderTodos(Jelly.todos)}
   </div>
   <div class="panel-footer">${Jelly.date}</div>
</div>
`
模板標籤字符串
const user='marry'
const topic="learn to use Markdown"

const sentence=highlight`${user} has commented on your topic ${topic}`

function highlight(strings,...values){
    debugger
}

strings與values

  • 變量在模板開頭或者結尾或多出空格
Local
strings: (3) ["", " has commented on your topic ", "", raw: Array(3)]
values: (2) ["marry", "learn to use Markdown"]
this: Window
const user='marry'
const topic="learn to use Markdown"

const sentence=highlight`${user} has commented on your topic ${topic}`

function highlight(strings,...values){
    const  highlighted=values.map(value =>
        `<span class="highlight">${value}</span>`
    )
    let str='';

    strings.forEach((string,i)=>
        str+=`${string}${highlighted[i]||''}`
    )
    return str

}

進化html裏輸入的腳本:sanitize

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章