Drupal मॉड्यूल में थीमिंग के लिए टेम्पलेट जोड़ना
Drupal 8 बेसिक मॉड्यूल्स बनाने की प्रैक्टिकल गाइड का भाग III
.info से लेकर टेस्ट तक, केवल बेसिक्स
loremipsum.module
/**
* Implements hook_theme().
*/
function loremipsum_theme($existing, $type, $theme, $path) {
$variables = array(
'loremipsum' => array(
'variables' => array(
'source_text' => NULL,
),
'template' => 'loremipsum',
),
);
return $variables;
}
.module फ़ाइल को न छोड़ने का एक और कारण यह है कि hook_theme() यहीं लिखा जाता है। यह D7 की तरह ही काम करता है: आप एक ऐरे परिभाषित करते हैं जिसमें आपके वेरिएबल्स और टेम्पलेट फ़ाइल होती है। टेम्पलेट फ़ाइल को सही स्थान (templates फ़ोल्डर) में .html.twig एक्सटेंशन के साथ रखना आवश्यक है।
फिर, Twig को रेंडर ऐरे पास करने से पहले आप कुछ प्रीप्रोसेसिंग कर सकते हैं। उदाहरण के लिए, नीचे दिया गया hook हर वाक्य के अंत में रैंडम विराम चिह्न डालता है:
/**
* Template preprocess function for Lorem ipsum.
*
* @param array $variables
* An associative array containing:
* - source_text
*/
function template_preprocess_loremipsum(&$variables) {
$punctuation = array('. ', '! ', '? ', '... ', ': ', '; ');
for ($i = 0; $i < count($variables['source_text']); $i++) {
$big_text = explode('. ', $variables['source_text'][$i]);
for ($j = 0; $j < count($big_text) - 1; $j++) {
$big_text[$j] .= $punctuation[floor(mt_rand(0, count($punctuation) - 1))];
}
$variables['source_text'][$i] = implode('', $big_text);
}
}
/templates/loremipsum.html.twig
{#
/**
* @file
* Lorem ipsum टेक्स्ट को प्रिंट करने के लिए डिफ़ॉल्ट थीम इम्प्लीमेंटेशन।
*
* उपलब्ध वेरिएबल्स:
* - source_text
*
* @see template_preprocess_loremipsum()
*
* @ingroup themeable
*/
#}
<div class="loremipsum">
{% for item in source_text %}
<p>{{ item }}</p>
{% endfor %}
</div>
अब $source_text ऐरे को हमारे Twig टेम्पलेट के अंदर एक साधारण for लूप के द्वारा प्रोसेस किया जाता है और <p> टैग्स में रैप किया जाता है।
ध्यान दें कि hook_theme(), template_preprocess_hook(), और हमारी Twig फ़ाइल के बीच सीधा संबंध है:


