简体   繁体   中英

How can I have simple macros in HTML?

I have a piece of HTML that I repeat frequently on a webpage but with some parts different. It contains some things inconvenient to write repeatedly, so I'd like to have a shortcut with parameters.

An example of how I would use it is to format dates. I format them like (2022‑04‑06) , where the entities are non-breaking hyphens. I want to not have to remember or copy the code for a non-breaking hyphen, so I'd like to be able to write it simply.

In LATEX, I could use a macro like this:

…
\newcommand{\mydate}[3]{(#1\nobreakdash-#2\nobreakdash-#3)}
\begin{document}
  \mydate{2022}{04}{06}
\end{document}

I know that HTML has custom tags, but I don't know how exactly they are supposed to be used. I imagine that the macro would be used like this:

<body>
  <my-date 2022 04 06>
</body>

I imagine that the macros would be defined in the head of the page, and a Javascript function would run when the page loads and format all the tags with defined macros.

How can be something like that achieved in HTML? I expect that it would involve a Javascript library. Then, I'd like that the library would be light and fast, and it would require not much boilerplate code.

This could be achieved by templates and preprocessing the webpage, but I don't want that; I want that I could quickly edit the page, save it, and it would be live.

You could use a templating engine like Handlebars . Just design your HTML template and define a custom helper function.

 const pad = (val, char, count) => (val + '').padStart(count, char); const parseTemplateHtml = (selector) => Handlebars.compile(document.querySelector(selector).innerHTML); Handlebars.registerHelper('formatDate', (year, month, date) => `${pad(year, '0', 4)}-${pad(month + 1, '0', 2)}-${pad(date, '0', 2)}`); const now = new Date(); const template = parseTemplateHtml('#my-date-template'); const context = { year: now.getFullYear(), month: now.getMonth(), date: now.getDate() }; document.body.innerHTML = template(context); // Rendered HTML;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script> <script id="my-date-template" type="text/x-handlebars-template"> <div class="my-date" data-value="{{formatDate year month date}}"> {{formatDate year month date}} </div> </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM