Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模板解析 #10

Open
xlearns opened this issue Oct 26, 2021 · 0 comments
Open

模板解析 #10

xlearns opened this issue Oct 26, 2021 · 0 comments

Comments

@xlearns
Copy link
Owner

xlearns commented Oct 26, 2021

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id='app'>
    <p>{{stage}} 平台课程:{{course.title}}</p>
    <h1>{{msg}}</h1>
  </div>
  <script>
    function compile(el,data){
      let fragment = document.createDocumentFragment()
      while(child = el.firstChild){
        //类似剪切
        fragment.appendChild(child)
      }
      
      function replace(dom){
        //(.*?)在能使整个匹配成功的前提下使用最少的重复
        let reg = /\{\{(.*?)\}\}/g
        Array.from(dom.childNodes).forEach(node=>{
          let textContent = node.textContent
          //拿到每一个结点
           //nodeType=3 表示代表元素或属性中的文本内容。
          //1表示元素、2表示属性
          if (node.nodeType === 3 && reg.test(textContent)) {
            const nodeTextContent = node.textContent
            const replaceText = () => {
            node.textContent = nodeTextContent.replace(reg, (matched, placeholder) => {
                  return placeholder.split('.').reduce((prev, key) => {
                      return prev[key]
                  }, data)
              })
            }
            replaceText()
          }
          // 如果还有子节点,继续递归 replace
            if (node.childNodes && node.childNodes.length) {
              replace(node)
            }
        })
      }
      replace(fragment)
      el.appendChild(fragment)
      return el
    }
    let data = {
      stage: 'GitChat',
      msg:"hello",
      course: {
          title: '前端开发进阶',
          author: 'Lucas',
          publishTime: '2018 年 5 月'
     }
    }
    //编译
    compile(document.querySelector('#app'), data)
  </script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant