Skip to content
Advertisement

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?

For instance, let’s say I have a snippet of code, which I’d like to keep separate. for now, we’ll call it snippet.php.

snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:

JavaScript

I’d like to be able to return this code from a function, along the lines of this:

JavaScript

I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.

Advertisement

Answer

One method is using file_get_contents and str_replace

HTML:

JavaScript

PHP:

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