Browse Source

fix #618 parsing html string without tag but with enitities

Evan You 11 năm trước cách đây
mục cha
commit
ef286ae47c
2 tập tin đã thay đổi với 13 bổ sung4 xóa
  1. 6 4
      src/parsers/template.js
  2. 7 0
      test/unit/specs/parsers/template_spec.js

+ 6 - 4
src/parsers/template.js

@@ -56,7 +56,8 @@ map.rect = [
   '</svg>'
 ]
 
-var TAG_RE = /<([\w:]+)/
+var tagRE = /<([\w:]+)/
+var entityRE = /&\w+;/
 
 /**
  * Convert a string template to a DocumentFragment.
@@ -75,16 +76,17 @@ function stringToFragment (templateString) {
   }
 
   var frag = document.createDocumentFragment()
-  var tagMatch = TAG_RE.exec(templateString)
+  var tagMatch = templateString.match(tagRE)
+  var entityMatch = entityRE.test(templateString)
 
-  if (!tagMatch) {
+  if (!tagMatch && !entityMatch) {
     // text only, return a single text node.
     frag.appendChild(
       document.createTextNode(templateString)
     )
   } else {
 
-    var tag    = tagMatch[1]
+    var tag    = tagMatch && tagMatch[1]
     var wrap   = map[tag] || map._default
     var depth  = wrap[0]
     var prefix = wrap[1]

+ 7 - 0
test/unit/specs/parsers/template_spec.js

@@ -37,6 +37,13 @@ if (_.inBrowser) {
       expect(res.firstChild.nodeType).toBe(3) // Text node
     })
 
+    it('should handle string that contains html entities', function () {
+      var res = parse('hi&lt;hi')
+      expect(res instanceof DocumentFragment).toBeTruthy()
+      expect(res.childNodes.length).toBe(1)
+      expect(res.firstChild.nodeValue).toBe('hi<hi')
+    })
+
     it('should parse textContent if argument is a script node', function () {
       var node = document.createElement('script')
       node.textContent = testString