diff --git a/.gitignore b/.gitignore index b966a55..ffb8df4 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ htmlcov/ compile_commands.json .idea/ .pytest_cache/ +.venv diff --git a/src/mwparserfromhell/nodes/template.py b/src/mwparserfromhell/nodes/template.py index ef0bcd1..e3abe79 100644 --- a/src/mwparserfromhell/nodes/template.py +++ b/src/mwparserfromhell/nodes/template.py @@ -17,7 +17,6 @@ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. - from collections import defaultdict import re @@ -33,7 +32,6 @@ FLAGS = re.DOTALL | re.UNICODE # Used to allow None as a valid fallback value _UNSET = object() - class Template(Node): """Represents a template in wikicode, like ``{{foo}}``.""" @@ -330,6 +328,17 @@ class Template(Node): self.params.append(param) return param + def update(self, params, **kwargs): + """Update the template with multiple parameters at once. + Args: + params: A dictionary mapping parameter names to values. + **kwargs: Optional arguments that will be applied to all parameters, + matching the same arguments in :meth:`add` (showkey, before, + after, preserve_spacing) + """ + for name, value in params.items(): + self.add(name, value, **kwargs) + def __setitem__(self, name, value): return self.add(name, value) diff --git a/tests/test_template.py b/tests/test_template.py index a67b9cd..475a468 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -394,6 +394,24 @@ def test_add(): assert "{{a|b=c|d=e|f=g|new_param=value}}" == node44 +def test_update(): + """test template.update()""" + node1 = Template(wraptext("a")) + node1.update({"b": "c", "d": "e"}) + assert "{{a|b=c|d=e}}" == node1 + + node2 = Template(wraptext("a")) + node2.update({"1": "b"}, showkey=False) + assert "{{a|b}}" == node2 + + node3 = Template(wraptext("a\n"), [ + pgens("b ", "c\n"), + pgens("d ", " e") + ]) + node3.update({"b ": "f"}, preserve_spacing=False) + assert "{{a\n|b =f|d = e}}" == node3 + + def test_remove(): """test Template.remove()""" node1 = Template(wraptext("foobar"))