简体   繁体   中英

How can I replace HTML with a razor helper in bulk (possibly using resharper search by pattern)?

I have some repeated HTML on a razor page which I want to replace with a razor helper. I'm using resharper 2017 and am hoping that the Search By Pattern feature will save me some time here, but I can't work out how to make it do what I want. I'm not sure if I'm trying to use it for the wrong purpose, or if I'm just using it badly.

This is (a small section of) the HTML I want to replace:

<li role="presentation" data-bind="visible: includeMtbf">
    <a href="#mtbf-tab" role="tab" data-toggle="tab">Rolling and Monthly MTBF</a>
</li>
<li role="presentation" data-bind="visible: includeMtbfWithoutMonthly">
    <a href="#rolling-mtbf-tab" role="tab" data-toggle="tab">Rolling MTBF</a>
</li>
<li role="presentation" data-bind="visible: includeMtbfByArea">
    <a href="#mtbf-by-location-tab" role="tab" data-toggle="tab">Rolling MTBF by Location</a>
</li>

I've written the following razor helper:

@helper BuildTab(string tabId, string inclusionVariable, string tabText)
{
    <li role="presentation" data-bind="visible: @inclusionVariable">
        <a href="#@tabId" role="tab" data-toggle="tab">@tabText</a>
    </li>  
}

Now I just need to replace the original HTML with calls to the helper:

@BuildTab("mtbf-tab", "includeMtbf", "Rolling and Monthly MTBF")
@BuildTab("rolling-mtbf-tab", "includeMtbfWithoutMonthly", "Rolling MTBF")
@BuildTab("mtbf-by-location-tab", "includeMtbfByArea", "Rolling MTBF by Location")

I've done them manually for the sake of clarifying what I'm trying to achieve, but is there a way to get resharper (or visual studio) to do this for me?

I've written the following pattern for resharper to search by:

<li role="presentation" data-bind="visible: $inclusionVariable$">
    <a href="#$tabId$" role="tab" data-toggle="tab">$tabText$</a>
</li>

but I can't work out how to set up the placeholder types to match the arbitrary text which could appear. With them set to Content Placeholder they don't match correctly, but none of the other types seem appropriate. Is this possible (either using resharper or a visual studio feature that I don't know about)?

I don't believe resharper can handle this, but it seems like a case for using regular expressions to find and replace in all files. Something like (untested): Find pattern

<li\s+role="presentation"\s+data-bind="visible:\s*(\w+)">\s*<a\s+href="#([\w\-]+)"\s+role="tab"\s+data-toggle="tab">([\w\s]+)</a>\s*</li>

Replace pattern

@BuildTab("$1", "$2", "$3")

Will all depend on how regular your original code is, but you might be able to modify the search regex to deal with irregularities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM