简体   繁体   中英

Using timber to render plugin pages

I am making a plugin which adds a bunch of pages to the admin view of WP. I'd really like to use Timber, specifically, the Twig templating functionality to render these pages.

While I have next to zero experience in WP and PHP in general, what attracts me to this approach is my previous familiarity with Django / Flask templates which allow me to extend a base template and specify blocks for header, content, footer. That seems trivial to do with Timber when using it to create a theme, but I can't for the life of me figure out how to make this setup work within a plugin. Sure, I can do something like this:

    add_action( 'admin_menu', 'test_setup_menu' );
    function test_setup_menu() {
        add_menu_page(
            'Tables',
            'Tables',
            'manage_options',
            'test-tables',
            'admin_page_test'
        );
    }

    function admin_page_test() {
        Timber::Render( 'test.twig');
    }

But that of course will render test.twig with header and footer parts already populated from the theme. The issue specifically is that I want to be able to add information to the header or footer blocks. I know I can do this like so:

add_action('admin_head', 'add_to_head')
function add_to_head() {
    ...
}

But this is precisely the type of thing I'm trying to avoid, I wish to encapsulate this type of logic in a Twig template. Is there any way to make this work?

Here's an example of how to add a custom admin page for a plugin.

<?php

/**
 * Plugin Name: Test Run
 */

  add_action('admin_menu', 'admin_menu_cb');

  function admin_menu_cb()
  {
    // Ref: https://developer.wordpress.org/reference/functions/add_menu_page/
    add_menu_page('Test Run Admin Page', 'Test Run', 'manage_options', 'test-run', 'render_menu_page_cb', 'dashicons-schedule', 3);
  }

  function render_menu_page_cb()
  {
    Timber::$locations = __DIR__.'/views';
    $data = [];
    Timber::render('main.twig', $data);
  }

For a more full example please see the below repo. I created it recently as a guide for anyone to use Timber in a wordpress plugin. https://github.com/chanakasan/a-wordpress-plugin-using-timber

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