I think that this depends on what the duplicated code looks like.
As an example, I have an application that has many dozens of videos, and counting. Each video is shown in a modal. This means that I would need many dozens of modals, one for each video.
The way that I have solved this is to use a button data attribute to send the info to the modal, as in
<button type="button" class="btn p-0" data-bs-toggle="modal" data-bs-target="#mdlVideo" data-bs-video="hp6gJLVUDjs" aria-label="Play Video">
This is for a youtube video with this link https://youtu.be/hp6gJLVUDjs
I then have the HTML-code for the modal and a bit of JS to apply the data, as in
<!-- MODAL FOR VIDEO -->
<div class="modal fade" id="mdlVideo" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" is="dmx-bs5-modal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-body">
<div class="ratio ratio-16x9">
<iframe title="YouTube video" allowfullscreen=""></iframe>
</div>
</div>
</div>
</div>
</div>
<script>
var videoModal = document.getElementById('mdlVideo')
videoModal.addEventListener('show.bs.modal', function (event) {
// Button that triggered the modal
var button = event.relatedTarget
// Extract info from data-bs-* attributes
var video = button.getAttribute('data-bs-video')
// Update the modal's content.
var modalBodyIframe = videoModal.querySelector('.modal-body iframe')
modalBodyIframe.src = 'https://www.youtube.com/embed/' + video + '?rel=0'
})
// Stop the video playing when modal is closed
videoModal.addEventListener('hidden.bs.modal', function (event) {
videoModal.querySelector('.modal-body iframe').src = ''
})
</script>
Hopefully, your code does not require the same amount of manipulation as my example, but it should give you an idea.
Which makes me wonder if I could not have used Workflows for the script bit. I have not used Workflows and know little about it.