Repeating a block of html like a function

2019-05-11 07:42发布

I am learning html, css and content management by building my own personal site, but I have very little experience in any of these areas. One thing that has bothered me is the amount I have to repeat a segment of "html code". For example, on my site I may have a block that looks like:

<div class="talk">
  <a href="link">
    title
    <div class="info">
      subtext
   </div>
  </a>
</div>

where link, title and subtext are the only elements that change. As a programmer, this looks like a function with three arguments: talk(link, title, subtext) and I would implement this by keeping a separate text file or database with all the entries and a program to "compile" the data and the HTML formatting into a final product. In fact, this is what I do now with a simple python script and BeautifulSoup. I have a feeling though, that there are tools out there for exactly this sort of thing, but there are so many options and systems I not even sure what I'm looking for exactly (Grunt, bower, Ruby on Rails, SASS, HMAL, handlebars, ...). This is not a request for recommendations, an acceptable answer could involve any framework, but I prefer simplicity over power.

What is canonical/standard way to do this? What is a minimal working example using my code block above?

1条回答
疯言疯语
2楼-- · 2019-05-11 08:13

Since you asked for a live example, here is one in PHP:

news_print.php

function output_some_news ($link, $title, $subtext)
{
    echo
"<div class='talk'>
     <a href='$link'>
         $title
        <div class='info'>
            $subtext
       </div>
     </a>
 </div>";
}

// this is just for show. Usually the data come from a database or data file
$topics = array (
    array ("http://celebslife.com", "Breaking news", "Justin Bieber just grew a second neuron"),
    array ("http://nerds.org"     , "New CSS draft available", "We won't be forced to use idiotic lists to implement menus in a foreseeable future"));

function output_news ($topics)
{
    foreach ($topics as $topic)
    {
        output_some_news  ($topic[0], $topic[1], $topic[2]);
    }
}

And from within your HTML page:

news.php

<?php include 'news_print.php'; ?>

<div class='news'>
    <?php output_news($topics); ?>
</div>

As for using PHP as a preprocessor, it is pretty straightforward:

C:\dev\php\news> php news.php > news.html

will produce pure HTML from your PHP script.

The PHP engine will be invoked from the command line instead of a web server, and its output will be stored in a file instead of being sent back to a browser, that's all.

Of course you will have some differences. For instance, all the web-specific informations like caller URL, cookies, etc. will not be available if you use PHP offline. On the other hand, you will be able to use command line arguments and environment variables.

查看更多
登录 后发表回答