PHP code example of lxbdr / wp-template-helper

1. Go to this page and download the library: Download lxbdr/wp-template-helper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lxbdr / wp-template-helper example snippets



$data = [
'foo' => 'bar',
'foo_url' => 'https://example.com',
'style' => 'color: red; font-weight: bold',
'img' => 'https://picsum.photos/100/100'
];

$t = new \Lxbdr\WpTemplateHelper\WpTemplateHelper($data);


$data = [
    'user' => [
        'name' => 'John Doe',
        'profile' => [
            'url' => 'https://example.com/john',
            'bio' => '<p>Web developer & WordPress enthusiast</p>'
        ]
    ]
];

$template = new WpTemplateHelper($data);

$name = $template->get('user.name'); // "John Doe"
$nonexistent = $template->get('user.foo'); // ""

if ($template->has('user.profile')) {
    // Access nested data
}

if ($template->notEmpty('user.bio')) {
    // Value exists and is not empty
}

if ($template->empty('user.location')) {
    // Value is empty or doesn't exist
}

$template->raw('user.name'); // Outputs: John Doe

$template = new WpTemplateHelper(['message' => 'Hello <world>']);
$template('message'); // Outputs: Hello &lt;world&gt;

// Safe HTML output with entities escaped
$template->html('user.name');

// Allow specific HTML tags (wp_kses_post)
$template->safeHtml('user.profile.bio');

// In HTML attributes
<a href=" $template->url('user.profile.url'); 

<div data-user=" $template->attr('user.name'); 

<script>
    const userName = " $template->js('user.name'); 

<?xml version="1.0"

// Bad
<a href=" $template->raw('link'); 

// Access deeply nested data
$template->html('user.settings.preferences.theme');

// Clean and secure template code
<div class="user-profile">
    <h2> $template->html('user.name'); 

$userName = $template->_html('user.name');
$profileUrl = $template->_url('user.profile.url');

// Use in complex logic
if ($template->has('user.profile') && $template->_url('user.profile.url')) {
    // Process data
}

// Static usage
WpTemplateHelper::_clsx(
    'btn',
    [
        'btn--primary' => true,
        'btn--large' => $isLarge,
        'btn--disabled' => !$isEnabled
    ],
    $additionalClasses
);

// Instance usage with data
$template = new WpTemplateHelper([
    'isActive' => true,
    'size' => 'large'
]);

<div class=" $template->clsx(
    'component',
    [
        'component--active' => $template->get('isActive'),
        'component--large' => $template->get('size') === 'large'
    ]
); 

// Static usage
<div style=" WpTemplateHelper::style([
    'display' => 'flex',
    'margin-top' => '20px',
    'color' => $textColor,
    'background' => $isDisabled ? '#ccc' : false
]); 

// Static usage
<div  WpTemplateHelper::attributes([
    'id' => 'main-content',
    'data-user' => $userName,
    'aria-label' => 'Main content area'
]); 

// Static usage
 WpTemplateHelper::heading('h1', 'Welcome to our site', [
    'class' => 'main-title',
    'id' => 'welcome-heading'
]); 

// Static usage

$tag = WpTemplateHelper::maybeAnchorTag(
    'https://example.com',
    ['class' => 'btn'],
    'span'
);
$tag->open();
echo 'Click me';
$tag->close();

// Static usage
 WpTemplateHelper::withLineBreaks([
    'First line',
    'Second line',
    '',  // Will be filtered out
    'Third line'
]); 

// Store result in variable
$classes = WpTemplateHelper::_clsx(['btn', 'btn--primary' => true]);
$styles = WpTemplateHelper::_style(['color' => 'red']);
$attributes = WpTemplateHelper::_attributes(['id' => 'main']);
$heading = WpTemplateHelper::_heading('h1', 'Title', ['class' => 'main']);
$content = WpTemplateHelper::_withLineBreaks(['Line 1', 'Line 2']);

// Using with conditions
if (WpTemplateHelper::_clsx(['active' => $condition])) {
    // Do something
}

$template = new WpTemplateHelper($data);

<div  $template->attributes([
    'class' => $template->_clsx([
        'component',
        'component--active' => $template->get('isActive')
    ]),
    'style' => $template->_style([
        'color' => $template->get('textColor')
    ])
]); 

// Instance usage
$template = new WpTemplateHelper([
    'title' => 'My Page',
    'content' => 'Page content'
]);

// Echo the ID
<div id=" $template->id('header'); 

$template = new WpTemplateHelper([]);
$prefix = $template->getIdPrefix(); // e.g., "abc12-"

// Useful for coordinating IDs with aria-labels or other references
<button id=" $template->id('trigger'); 

$template = new WpTemplateHelper([]);

// Initial prefix
echo $template->getIdPrefix(); // e.g., "abc12-"

// Generate new prefix
$template->regenerateIdPrefix();
echo $template->getIdPrefix(); // e.g., "xyz89-"

$template = new WpTemplateHelper([
    'tabs' => [
        ['title' => 'Tab 1', 'content' => 'Content 1'],
        ['title' => 'Tab 2', 'content' => 'Content 2']
    ]
]);

$template = new WpTemplateHelper([
    'fields' => [
        'name' => 'Full Name',
        'email' => 'Email Address',
        'message' => 'Your Message'
    ]
]);

// Using a WordPress image ID
$data = ['profile_image' => 123];
$template = new WpTemplateHelper($data);

// Echo the image
$template->img('profile_image');
// Output: <img src="path/to/image.jpg" alt="Image Alt Text">

// With custom size and attributes
$template->img('profile_image', 'thumbnail', ['class' => 'rounded']);
// Output: <img src="path/to/thumbnail.jpg" alt="Image Alt Text" class="rounded">

// Using direct URL
$data = ['hero_image' => 'https://example.com/image.jpg'];
$template->img('hero_image');
// Output: <img src="https://example.com/image.jpg" alt="">

// Using array with URL and alt text
$data = [
    'team_member' => [
        'url' => 'https://example.com/member.jpg',
        'alt' => 'Team Member Photo'
    ]
];
$template->img('team_member');
// Output: <img src="https://example.com/member.jpg" alt="Team Member Photo">

$data = [
    'hero' => [
        'base_img' => [
            'url' => 'path/to/mobile.jpg',
            'alt' => 'Hero Image'
        ],
        'sources' => [
            [
                'img_id' => 123, // WordPress image ID
                'media_query' => '(min-width: 768px)'
            ],
            [
                'img_id' => 456,
                'media_query' => '(min-width: 1024px)'
            ]
        ]
    ]
];

$template = new WpTemplateHelper($data);
$template->responsiveImg('hero');

// Output:
// <picture>
//     <source media="(min-width: 1024px)" srcset="path/to/desktop.jpg 1200w" sizes="100vw">
//     <source media="(min-width: 768px)" srcset="path/to/tablet.jpg 800w" sizes="100vw">
//     <img src="path/to/mobile.jpg" alt="Hero Image">
// </picture>

$data = [
    'featured' => [
        'sizing' => 'width-full-height-full',
        'custom_width' => '500px',
        'custom_height' => '300px',
        'focal_x' => '30',
        'focal_y' => '70',
        'object_fit' => 'cover',
        'display' => 'block',
        'base_img' => [
            'url' => 'path/to/image.jpg',
            'alt' => 'Featured Image'
        ],
        'sources' => [] // Optional responsive sources
    ]
];

$template = new WpTemplateHelper($data);
$template->advancedImg('featured');

// Output:
// <div class="lx-img lx-img--full-width lx-img--full-height lx-img--cover lx-img--block" 
//      style="--width: 500px; --height: 300px; --focal-x: 30%; --focal-y: 70%">
//     <picture>
//         <img src="path/to/image.jpg" alt="Featured Image">
//     </picture>
// </div>

// In your theme's functions.php or plugin file
add_action('wp_head', function() {
    echo '<style>' . WpTemplateHelper::getAdvancedImgCss() . '</style>';
});

// Or via enqueue scripts to attach it to an existing handle
add_action('wp_enqueue_scripts', function() {
	$style = \Lxbdr\WpTemplateHelper\WpTemplateHelper::getAdvancedImgCss();
	wp_add_inline_style('wp-block-library', $style);
});

\add_action( 'acf/init', function () {

	\Lxbdr\WpTemplateHelper\WpTemplateHelper::registerAdvancedImgAcfFields();
} );

array(
			'key' => 'field_672e120b01cf8',
			'label' => 'Clone img group wrapper',
			'name' => 'clone_img_group_wrapper',
			'aria-label' => '',
			'type' => 'group',
			'instructions' => '',
			'2e122901cf9',
					'label' => 'clone_img_group',
					'name' => 'clone_img_group',
					'aria-label' => '',
					'type' => 'clone',
					'instructions' => '',
					' = get_field('clone_img_group_wrapper');

// and using the WpTemplateHelper
$data = [
'my_img' => get_field('clone_img_group_wrapper')
];
$t = new \Lxbdr\WpTemplateHelper\WpTemplateHelper($data);
$t->advancedImg('my_img');