اذهب إلى المحتوى
  • 0

كيف يمكنني برمجة نظام قوالب يستخدم ملفات tpl لسكربت php

NAIF

السؤال

السلام عليكوم ورحمة الله و بركاته 

لوسمحتم انا ابرمج سكربت php و العميل يحتاج يضيف خيار في لوحة التحكم 

للتحكم بشكل الموقع فأنا افكر بعمل نظام قوالب بسيط يستخدم ملفات tpl

و ايضا يمكنة التعديل على كود القالب من لوحة التحكم 

بحيث يكون في جذر الموقع مجلد template و بداخلة مجلدات القوالب.

كيف يمكنني إضافة الميزة في السكربت ؟؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

أولاً، عليك بتنظيم هيكل المجلدات في مشروعك إنشاء مجلد templates في جذر المشروع، وداخله مجلدات للقوالب المختلفة.

/your-project
    /templates
        /template1
            header.tpl
            footer.tpl
            index.tpl
        /template2
            header.tpl
            footer.tpl
            index.tpl
    /admin
        edit_template.php
    index.php
    template_engine.php

ثم كتابة كود بسيط لتحميل القوالب  في ملف وليكن باسم TemplateEngine.php وسيكون مسؤول عن ترجمة ملفات .tpl واستبدال الـ placeholders ببيانات فعلية.

class TemplateEngine {
    private $templateDir;

    public function __construct($templateDir) {
        $this->templateDir = $templateDir;
    }

    public function render($templateName, $data) {
        $templateFile = $this->templateDir . '/' . $templateName . '.tpl';
        if (!file_exists($templateFile)) {
            throw new Exception("Template file not found: $templateFile");
        }

        $templateContent = file_get_contents($templateFile);
        foreach ($data as $key => $value) {
            $templateContent = str_replace('{' . $key . '}', $value, $templateContent);
        }

        return $templateContent;
    }
}

ثم إنشاء مدير للقوالب TemplateManager ليكون مسؤول عن إنشاء وتعديل وحذف القوالب:

class TemplateManager {
    private $templateDir;
    private $templateEngine;

    public function __construct($templateDir) {
        $this->templateDir = $templateDir;
        $this->templateEngine = new TemplateEngine($templateDir);
    }

    public function getTemplates() {
        $templates = scandir($this->templateDir);
        $templates = array_filter($templates, function ($file) {
            return substr($file, -4) === '.tpl';
        });
        return $templates;
    }

    public function getTemplateContent($templateName) {
        $templateFile = $this->templateDir . '/' . $templateName . '.tpl';
        return file_get_contents($templateFile);
    }

    public function saveTemplateContent($templateName, $content) {
        $templateFile = $this->templateDir . '/' . $templateName . '.tpl';
        file_put_contents($templateFile, $content);
    }

    public function renderTemplate($templateName, $data) {
        return $this->templateEngine->render($templateName, $data);
    }
}

بعد ذلك تستطيع استخدام TemplateManager في إدارة القوالب، قم بإنشاء نسخة من الكلاس لاستخدام الميثودز الخاصة به.

مثلاً تستطيع إنشاء صفحة في لوحة التحكم تقوم بها بعرض جميع القوالب، ثم السماح للمديرين بتعديل القالب بالضغط عليه وعند الإنتهاء من التعديل تستخدم ميثود saveTemplateContent لحفظ التعديلات والقالب، وهكذا.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

أول خطوة نقوم بتنظيم ملفات القوالب وذلك من خلال إنشاء مجلد `templates` في جذر الموقع، ونضع بداخله مجلدات لكل قالب بحيث يكون لكل مجلد قالب يحتوي على ملفات `.tpl` الخاصة به هكذا:

project_root/
|-- templates/
|   |-- template1/
|   |   |-- header.tpl
|   |   |-- footer.tpl
|   |   |-- index.tpl
|   |-- template2/
|       |-- header.tpl
|       |-- footer.tpl
|       |-- index.tpl
|-- other_files_and_folders/

لإعداد نظام القوالب نستخدم مكتبة مثل Smarty لتسهيل الأمر، نقوم بتثبيتها من خلال ال Composer 

composer require smarty/smarty

ثم نقوم بإعداد ملف php:

require_once('vendor/autoload.php');

$smarty = new Smarty;

$template = isset($_GET['template']) ? $_GET['template'] : 'default';
$templatePath = __DIR__ . "/templates/{$template}";

$smarty->setTemplateDir($templatePath);
$smarty->setCompileDir('templates_c');
$smarty->setCacheDir('cache');
$smarty->setConfigDir('configs');

// Assign variables and display template
$smarty->assign('name', 'Abdelouahab');
$smarty->display('index.tpl');

ثم نقوم بإنشاء صفحة في لوحة التحكم لعرض وتعديل ملفات القوالب بهذا الشكل:

$templatesDir = __DIR__ . '/templates';
$templates = array_diff(scandir($templatesDir), ['..', '.']);

foreach ($templates as $template) {
    echo "<a href='edit_template.php?template={$template}'>{$template}</a><br>";
}

صفحة تعديل القالب:

$template = isset($_GET['template']) ? $_GET['template'] : '';
$filepath = __DIR__ . "/templates/{$template}/index.tpl";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    file_put_contents($filepath, $_POST['content']);
}

$content = file_get_contents($filepath);
?>

<form method="post">
    <textarea name="content" rows="20" cols="80"><?= htmlspecialchars($content) ?></textarea><br>
    <input type="submit" value="Save">
</form>

ثم نضيف جدول في قاعدة البيانات لحفظ القالب المختار من قبل المستخدم:

CREATE TABLE settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template VARCHAR(255) NOT NULL
);

ثم نقوم بحفظ القالب:

$template = $_POST['template'];
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("UPDATE settings SET template = ? WHERE id = 1");
$stmt->execute([$template]);

ثم نستخدمه من خلال هذه الشيفرة:

$stmt = $pdo->query("SELECT template FROM settings WHERE id = 1");
$template = $stmt->fetchColumn();
$templatePath = __DIR__ . "/templates/{$template}";

$smarty->setTemplateDir($templatePath);
$smarty->assign('name', 'Abdelouahab');
$smarty->display('index.tpl');

وأخيرا في لوحة التحكم، نقوم بإضافة خيار لتحديد القالب الحالي من خلال إنشاء قائمة منسدلة (Dropdown) لاختيار القالب، وتحديث القيمة في قاعدة البيانات عند التغيير هكذا:

$templatesDir = __DIR__ . '/templates';
$templates = array_diff(scandir($templatesDir), ['..', '.']);

echo "<form method='post'>";
echo "<select name='template'>";
foreach ($templates as $template) {
    echo "<option value='{$template}'>{$template}</option>";
}
echo "</select>";
echo "<input type='submit' value='Save'>";
echo "</form>";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedTemplate = $_POST['template'];
    $stmt = $pdo->prepare("UPDATE settings SET template = ? WHERE id = 1");
    $stmt->execute([$selectedTemplate]);
}
تم التعديل في بواسطة عبد الوهاب بومعراف
رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ 14 ساعة قال عبد الوهاب بومعراف:

أول خطوة نقوم بتنظيم ملفات القوالب وذلك من خلال إنشاء مجلد `templates` في جذر الموقع، ونضع بداخله مجلدات لكل قالب بحيث يكون لكل مجلد قالب يحتوي على ملفات `.tpl` الخاصة به هكذا:

project_root/
|-- templates/
|   |-- template1/
|   |   |-- header.tpl
|   |   |-- footer.tpl
|   |   |-- index.tpl
|   |-- template2/
|       |-- header.tpl
|       |-- footer.tpl
|       |-- index.tpl
|-- other_files_and_folders/

لإعداد نظام القوالب نستخدم مكتبة مثل Smarty لتسهيل الأمر، نقوم بتثبيتها من خلال ال Composer 

composer require smarty/smarty

ثم نقوم بإعداد ملف php:

require_once('vendor/autoload.php');

$smarty = new Smarty;

$template = isset($_GET['template']) ? $_GET['template'] : 'default';
$templatePath = __DIR__ . "/templates/{$template}";

$smarty->setTemplateDir($templatePath);
$smarty->setCompileDir('templates_c');
$smarty->setCacheDir('cache');
$smarty->setConfigDir('configs');

// Assign variables and display template
$smarty->assign('name', 'Abdelouahab');
$smarty->display('index.tpl');

ثم نقوم بإنشاء صفحة في لوحة التحكم لعرض وتعديل ملفات القوالب بهذا الشكل:

$templatesDir = __DIR__ . '/templates';
$templates = array_diff(scandir($templatesDir), ['..', '.']);

foreach ($templates as $template) {
    echo "<a href='edit_template.php?template={$template}'>{$template}</a><br>";
}

صفحة تعديل القالب:

$template = isset($_GET['template']) ? $_GET['template'] : '';
$filepath = __DIR__ . "/templates/{$template}/index.tpl";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    file_put_contents($filepath, $_POST['content']);
}

$content = file_get_contents($filepath);
?>

<form method="post">
    <textarea name="content" rows="20" cols="80"><?= htmlspecialchars($content) ?></textarea><br>
    <input type="submit" value="Save">
</form>

ثم نضيف جدول في قاعدة البيانات لحفظ القالب المختار من قبل المستخدم:

CREATE TABLE settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template VARCHAR(255) NOT NULL
);

ثم نقوم بحفظ القالب:

$template = $_POST['template'];
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("UPDATE settings SET template = ? WHERE id = 1");
$stmt->execute([$template]);

ثم نستخدمه من خلال هذه الشيفرة:

$stmt = $pdo->query("SELECT template FROM settings WHERE id = 1");
$template = $stmt->fetchColumn();
$templatePath = __DIR__ . "/templates/{$template}";

$smarty->setTemplateDir($templatePath);
$smarty->assign('name', 'Abdelouahab');
$smarty->display('index.tpl');

وأخيرا في لوحة التحكم، نقوم بإضافة خيار لتحديد القالب الحالي من خلال إنشاء قائمة منسدلة (Dropdown) لاختيار القالب، وتحديث القيمة في قاعدة البيانات عند التغيير هكذا:

$templatesDir = __DIR__ . '/templates';
$templates = array_diff(scandir($templatesDir), ['..', '.']);

echo "<form method='post'>";
echo "<select name='template'>";
foreach ($templates as $template) {
    echo "<option value='{$template}'>{$template}</option>";
}
echo "</select>";
echo "<input type='submit' value='Save'>";
echo "</form>";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedTemplate = $_POST['template'];
    $stmt = $pdo->prepare("UPDATE settings SET template = ? WHERE id = 1");
    $stmt->execute([$selectedTemplate]);
}

شكرا لكم جميعا. اخي الفاضل ممكن تعملي مثال كود صفحة تعديل القالب  وصفحة تثبيت القالب على الموقع 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0
بتاريخ 16 دقائق مضت قال NAIF:

شكرا لكم جميعا. اخي الفاضل ممكن تعملي مثال كود صفحة تعديل القالب  وصفحة تثبيت القالب على الموقع 

حسنا هذا مثال باستخدام مكتبة Smarty. لنبدأ أولا بصفحة تعديل القالب التي ستسمح للمستخدم بتحرير محتوى ملفات القالب من خلال لوحة التحكم.

<?php
require_once('init.php');

$template = isset($_GET['template']) ? $_GET['template'] : 'default';
$templateDir = __DIR__ . "/templates/{$template}";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $filepath = $templateDir . '/' . $_POST['file'];
    file_put_contents($filepath, $_POST['content']);
    echo "Template updated successfully!";
}

$files = array_diff(scandir($templateDir), ['..', '.']);
$selectedFile = isset($_POST['file']) ? $_POST['file'] : (reset($files) ?: '');
?>

ولتثبيته هذا مثال عليه:

<!DOCTYPE html>
<html>
<head>
    <title>Edit Template</title>
</head>
<body>
    <h1>Edit Template: <?php echo htmlspecialchars($template); ?></h1>
    <form method="get">
        <label for="template">Select Template:</label>
        <select name="template" id="template" onchange="this.form.submit()">
            <?php
            $templates = array_diff(scandir(__DIR__ . '/templates'), ['..', '.']);
            foreach ($templates as $tpl) {
                echo "<option value='{$tpl}'" . ($tpl == $template ? ' selected' : '') . ">{$tpl}</option>";
            }
            ?>
        </select>
    </form>
    <form method="post">
        <label for="file">Select File:</label>
        <select name="file" id="file" onchange="this.form.submit()">
            <?php
            foreach ($files as $file) {
                echo "<option value='{$file}'" . ($file == $selectedFile ? ' selected' : '') . ">{$file}</option>";
            }
            ?>
        </select>
        <br>
        <textarea name="content" rows="20" cols="80"><?php echo htmlspecialchars(file_get_contents($templateDir . '/' . $selectedFile)); ?></textarea>
        <br>
        <input type="submit" value="Save">
    </form>
</body>
</html>
رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...