Commits

Gael Pasgrimaud committed 56528aa

add wrap(). add a few docstring for api documentation

  • Participants
  • Parent commits 5417981

Comments (0)

Files changed (2)

pyquery/pyquery.py

         return self
 
     def text(self, value=no_default):
-        """return the text representation of sub nodes
+        """Get or set the text representation of sub nodes::
+
+            >>> doc = PyQuery('<div><span>toto</span><span>tata</span></div>')
+            >>> print doc.text()
+            toto tata
+
+            >>> doc.text('Youhou !')
+            [<div>]
+            >>> print doc
+            <div>Youhou !</div>
+
         """
 
         if value is no_default:
         value.before(self)
         return self
 
+    def wrap(self, value):
+        """A string of HTML that will be created on the fly and wrapped around
+        each target::
+
+            >>> d = PyQuery('<span>youhou</span>')
+            >>> d.wrap('<div></div>')
+            [<div>]
+            >>> print d
+            <div><span>youhou</span></div>
+        """
+        assert isinstance(value, basestring)
+        value = fromstring(value)
+        nodes = []
+        for tag in self:
+            wrapper = deepcopy(value)
+            # FIXME: using iterchildren is probably not optimal
+            childs = [c for c in wrapper.iterchildren()]
+            if not childs:
+                child = wrapper
+            else:
+                child = childs[-1]
+            child.append(deepcopy(tag))
+            nodes.append(child)
+
+            parent = tag.getparent()
+            if parent is not None:
+                index = parent.index(tag)
+                # FIXME: using iterchildren is probably not optimal
+                for t in parent.iterchildren():
+                    if t is tag:
+                        t.addnext(child)
+                        parent.remove(t)
+                        break
+        self[:] = nodes
+        return self
+
     def replaceWith(self, value):
         """replace nodes by value
         """
         >>> pq('<ul> <li>  </li> </ul>').text()
         ''
 
-        >>> print pq('<ul><li>toto</li><li>tata</li></ul>').text()
-        toto tata
-
         >>> print pq('<ul> <li> toto </li> <li> tata </li> </ul>').text()
         toto tata
 
     """
 
+def test_wrap():
+    """
+    Complex wrapping::
+
+        >>> d = pq('<div id="bouh"><span>youhou</span></div>')
+        >>> s = d('span')
+        >>> s is d
+        False
+        >>> s.wrap('<div id="wrapper"></div>')
+        [<div#wrapper>]
+
+    We get the original doc with new node::
+
+        >>> print d
+        <div id="bouh"><div id="wrapper"><span>youhou</span></div></div>
+    """
+
 class DocTest(doctest.DocFileCase):
 
     path = os.path.join(dirname, 'README.txt')