Mojo: Content boxes like "Widgets"

Tags:

When we create a sidebar, generally we would like to suppress emitting the wrapper and title of our "widgets" (yes, I am still coming from the view of a developer too long having done nothing but WordPress) when there is no content "in the box."

In code, we can examine the currently defined stash data or content areas like this:

if (length($c->content('content')) { … }

Note that, at least as of Mojolicious 6.0, content() will actually create an empty content area even if not given any content, so we must test length(); for stash data, we probably would use defined instead.

We can do this inside a template too. Here's an example for both content and stash:

#!/usr/bin/env perl

use Mojolicious::Lite;

# setup base route
any '/' => sub {
  my $self = shift;

  # Example stash data and content
  $self->stash( text2 => 'some text' );
  $self->content( area3 => 'some text' );
  $self->render('index');
};

app->start;

__DATA__

@@ index.html.ep

<!DOCTYPE html>
<html>
<head><title>Widget Boxes</title></head>
<body>

  % if (defined stash('text1')) {
      <b><%= stash('text1') %></b>
  % } else {
      <em>No content</em>
  % }

<hr width='50%'>
  % if (defined stash('text2')) {
      <b><%= stash('text2'); %></b>
  % } else {
      <em>No content</em>
  % }

<hr>

  % if (length content('area1')) {
      <b><%= content('area1') %></b>
  % } else {
      <em>No content</em>
  % }
<hr width='50%'>

  % if (length content('area2')) {
      <b><%= content('area2') %></b>
  % } else {
      <em>No content</em>
  % }
<hr width='50%'>

  % if (length content('area3')) {
      <b><%= content('area3') %></b>
  % } else {
      <em>No content</em>
  % }

</body>
</html>