Reusing code

Today has been quite a day learning loads of new Wappler features and techniques.

I have a chunk of HTML - only about 6 lines - which will be used a number of times in the page. It references a couple of dynamic values but apart from that, it’s identical.

Duplicating it feels like a bad solution so I want to create it and then call it each time.

In PHP I would create a function. What’s the best way in Wappler?

1 Like

Isn’t what Library is for? Just thinking out loud.

Use a partial file include (if using NodeJS)

Sorry, I’m using PHP and it’s the front end I’m wanting to reuse code, not server connect so the library isn’t an option.

PHP includes or requires maybe?

1 Like

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

I then have the HTML-code for the modal and a bit of JS to apply the data, as in

	<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>
		var videoModal = document.getElementById('mdlVideo')
    videoModal.addEventListener('', 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 = '' + video + '?rel=0'
	// Stop the video playing when modal is closed
    videoModal.addEventListener('', function (event) {
        videoModal.querySelector('.modal-body iframe').src = ''

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.

@sitestreet, so far I’ve got away with php includes and setting various variables that the reusable code references…

Thanks everyone. I did it with includes and good old-fashioned PHP variables. :slight_smile: