template.ts 856 B

123456789101112131415161718192021222324252627282930
  1. import { adoptTemplate, currentHydrationNode, isHydrating } from './hydration'
  2. import { child, createTextNode } from './node'
  3. let t: HTMLTemplateElement
  4. /*! #__NO_SIDE_EFFECTS__ */
  5. export function template(html: string, root?: boolean) {
  6. let node: Node
  7. return (): Node & { $root?: true } => {
  8. if (isHydrating) {
  9. if (__DEV__ && !currentHydrationNode) {
  10. // TODO this should not happen
  11. throw new Error('No current hydration node')
  12. }
  13. return adoptTemplate(currentHydrationNode!, html)!
  14. }
  15. // fast path for text nodes
  16. if (html[0] !== '<') {
  17. return createTextNode(html)
  18. }
  19. if (!node) {
  20. t = t || document.createElement('template')
  21. t.innerHTML = html
  22. node = child(t.content)
  23. }
  24. const ret = node.cloneNode(true)
  25. if (root) (ret as any).$root = true
  26. return ret
  27. }
  28. }