Page width theme setting

Create a theme setting to set the page layout width.

Config schema and default config

mantratheme/config/schema/mantratheme.schema.yml

mantratheme.settings:
  type: theme_settings
  label: 'Mantra settings'
  mapping:
    page_width:
      type: string
      label: Page width

mantratheme/config/install/mantratheme.settings.yml

page_width: medium

Settings form

Add a settings form to set the value and use it in the page template.

All you have to do is add a theme-settings.php file in your theme directory and use a special form alter.

/**
 * Implements hook_form_system_theme_settings_alter().
 */
function mantratheme_form_system_theme_settings_alter(&$form, &$form_state) {

  $form['mantratheme'] = [
    '#type' => 'details',
    '#title' => t('Mantra'),
    '#open' => TRUE,
  ];

  $form['mantratheme']['page_width'] = [
    '#type' => 'select',
    '#title' => t('Page width (rem)'),
    '#options' => [
      'small' => t('Small (36)'),
      'medium' => t('Medium (42)'),
      'large' => t('Large (64)')
    ],
    '#default_value' => theme_get_setting('page_width'),
  ];

}

Page template class

Set the variable in a preprocess hook.

mantratheme.theme

function mantratheme_preprocess_page(&$variables) {
  $page_width = theme_get_setting('page_width');
  if (empty($page_width)) {
    $page_width = 'medium';
  }

  switch ($page_width) {
    case 'small':
      $page_width_rem = 36;
      break;
    case 'medium':
      $page_width_rem = 42;
      break;
    case 'large':
      $page_width_rem = 64;
      break;
  }
  $variables['page_width'] = "page-width-$page_width_rem";
}

page.html.twig

<div class="layout-container {{ page_width }}">

layout.css

.layout-container.page-width-36  {
  max-width: 36rem;
}

.layout-container.page-width-42  {
  max-width: 42rem;
}

.layout-container.page-width-64 {
  max-width: 64rem;
}

 

Topics