earwig / mwparserfromhell

A Python parser for MediaWiki wikicode
https://mwparserfromhell.readthedocs.io/
MIT License
741 stars 74 forks source link

Filter subtemplates? #273

Closed RheingoldRiver closed 3 years ago

RheingoldRiver commented 3 years ago

Is there a way to do this? I want to ideally run filter_templates() on a Template object, or on a Parameter object, without ever using str() and then re-parsing, but neither of these seems possible, is there something similar I can do?

The use case is: I'm given a template, which has a parameter with a value I need to work with, get some information from, and then use this information to update all of the children of a certain type, which are themselves templates, something like this:

{{Scoreboard/Season 8|match_history=link
|player1={{Scoreboard/Player|params|to|update}}
|player2={{Scoreboard/Player|params|to|update}}
|player3={{Scoreboard/Player|params|to|update}}
|player4={{Scoreboard/Player|params|to|update}}
...etc
}}

The best way I can see is to be to get the value of each player as a string, then re-parse this as a Wikicode object so I can get a template from it, but this seems rather roundabout. I might just be missing something in the documentation though.

Thanks!

JJMC89 commented 3 years ago

You should only need to parse once.

You can call filter_templates() on the parameter name or value (which are Wikicode), but not Parameter.

# Assuming that tpl is the outer template
for param in tpl.params:
    if not param.name.strip().startswith('player'):
        continue
    player_tpl = param.value.filter_templates()[0]  # assuming there is always one template in a player parameter
RheingoldRiver commented 3 years ago

Thanks, yeah that works. It needs a type hint to not get marked as an error, but that's fine