Commits

Anonymous committed 8376a53

Allow replaceWith() to take a lambda

  • Participants
  • Parent commits a031a26

Comments (0)

Files changed (2)

File pyquery/pyquery.py

     def replaceWith(self, value):
         """replace nodes by value
         """
-        for tag in self:
-            self.__class__(tag).before(value + (tag.tail or ''))
-            parent = tag.getparent()
-            parent.remove(tag)
+        if callable(value):
+            for i, element in enumerate(self):
+                self.__class__(element).before(value(i, element) + (element.tail or ''))
+                parent = element.getparent()
+                parent.remove(element)
+        else:
+            for tag in self:
+                self.__class__(tag).before(value + (tag.tail or ''))
+                parent = tag.getparent()
+                parent.remove(tag)
         return self
 
     def replaceAll(self, expr):

File pyquery/test.py

 	val = d.__html__()
         assert val == expected, repr(val)
 
+    def test_replaceWith_with_function(self):
+        expected = '''<div class="portlet">
+      Test<img src="myimage">My link text
+      <img src="myimage2">My link text 2
+    </div>'''
+        d = pq(self.html)
+        d('a').replaceWith(lambda i, e: pq(e).html())
+	val = d.__html__()
+        assert val == expected, repr(val)
+
 if __name__ == '__main__':
     fails, total = unittest.main()
     if fails == 0: