Skip to content
Advertisement

Include HTML markup from another file inside PHP file

So this is the method that I am using and it’s kinda working, but I don’t think that it’s best practice and just seems kinda off, so I wanted to see if someone knew a much better and/or cleaner method on importing HTML markup that will be located in two locations.

So let’s say that I have my main index.php file:

$mode = get_field('mode');
<?php if ($mode == 'page'): ?>
    <div class="container my-4 <?= $class_name?>">
        <div class="row justify-content-md-center pardot-form">
            <div class="col-md-6 col-lg-6">
                <h3>Pardot Form</h3>
                <?php include_once 'pardot-form.php'?>
            </div>
        </div>
    </div>
<?php else: ?>
    <div class="modal_element" data-toggle="modal" data-target="#modal-<?= $id ?>" data-cookie="<?= get_field('cookie'); ?>"></div>
    <div class="modal fade" id="modal-<?= $id ?>" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Pardot Form</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">✕</span>
                    </button>
                </div>
                <div class="modal-body">
                    <?php include_once 'pardot-form.php'?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

Then I am calling <?php include_once 'pardot-form.php'?> in two locations because I don’t want to repeat the same HTML output twice, so the pardot-form.php file contains the following:

<form class="form">
    <div class="form-group">
        <label for="formGroupExampleInput">First Name:</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input placeholder">
    </div>
    <div class="form-group">
        <label for="formGroupExampleInput2">Last Name:</label>
        <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input placeholder">
    </div>
    <div class="my-3">
        <button type="submit" class="btn btn-primary" disabled>Submit</button>
    </div>
</form>

Is there a cleaner way to “Grab HTML markup and append it in two locations”, the only difference is the outer layer where one conditional is a container block and another is a modal.

I can even delete the pardot-form.php file and add in the HTML markup in the same index.php file if you know of a cleaner way.

All help is appreciated!

Advertisement

Answer

You could save include_once 'pardot-form.php' to a variable under the $mode = get_field('mode'); declaration and then use it wherever you want.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement