Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Parser szablonów
Forum PHP.pl > Forum > PHP
akurczyk
Napisałem parser szablonów.
index.php:
  1. <?php
  2. class template {
  3. var $sSource;
  4. var $sParsed;
  5. var $aValues = array();
  6. function load($sTemplate) {
  7. return (!$this->sSource = @file_get_contents($sTemplate)) ? false : true;
  8. }
  9. function init($sKey, $sValue) {
  10. $this->aValues[$sKey] = $sValue;
  11. }
  12. function run() {
  13. print preg_replace('/{(.+?)}/e', '$this->aValues['1']', $this->sSource);
  14. }
  15. }
  16. $tpl = new template;
  17. $tpl -> load("template.html");
  18. $tpl -> init("{TITLE}", "Tytuł strony");
  19. $tpl -> init("{CONTENT}", "Treść strony");
  20. $tpl -> run();
  21. ?>


template.html:
  1. <title>{TITLE}</title>
  2. </head>
  3. {CONTENT}
  4. </body>
  5. </html>


Dlaczego to niechce działać?
Co napisałem źle?
Cysiaczek
1. Dodaj bbcode do listingu
2. Komunikat błędu
3. Przenoszę na PHP
wrzasq
twoje wyrazenie ma postac: {(.+?)}, czyli pierwsze dopasowanie bedzie tylko tym co jest pomiedzy nawiasami klamrowymy, a ty masz jako klucze tablicy zmiennych wyrazenia wlacznie z klamrami. czyli twoje wyrazenie zamiast {TITLE} i {CONTENT} dopasowuje samo TITLE i CONTENT. roziazania sa dwa:

albo:
  1. <?php
  2. print preg_replace('/{(.+?)}/e', '$this->aValues['{1}']', $this->sSource);
  3. ?>

albo:
  1. <?php
  2. print preg_replace('/{(.+?)}/e', '$this->aValues['']', $this->sSource);
  3. ?>
akurczyk
Dzięki działa!!!
Wybrałem to drugie.

Teraz parser wygląda tak:
  1. <?php
  2. class template {
  3. var $source;
  4. var $values = array();
  5. function load($file) {
  6. return($this->source = file_get_contents($file));
  7. }
  8. function init($key, $value) {
  9. $this->values[$key] = $value;
  10. }
  11. function run() {
  12. echo preg_replace('/{(.+?)}/e', '$this->values['{1}']', $this->source);
  13. }
  14. }
  15. $tpl = new template;
  16. $tpl -> load("template.html");
  17. $tpl -> init("{TITLE}", "Tytuł strony");
  18. $tpl -> init("{CONTENT}", "Treść strony");
  19. $tpl -> run();
  20. ?>
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.