0

How do I display a variable in my template?

I have the following code:

<?php
namespace Craft;

class HelloPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('Hello');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Richard G.';
    }

    function getDeveloperUrl()
    {
        return 'http://example.com';
    }

        public function hasCpSection()
    {
        return true;
    }

}

plugins/hello/variables/HelloVariable

<?php
namespace Craft;

class HelloVariable
{
    // property
    $message = 'Hello, World";"
 }


plugins/hello/templates/index.html

{% extends "_layouts/cp" %}

{% set title = "Hello World"|t %}

{% set content %}

<h2>MessageVariable  {{ craft.helloPlugin.HelloVariable.message }}</h2>

{% endset %}
6

Within your variables class file you will want to define methods that 'return' values to your template, like so:

class HelloVariable
{
    public function message()
    {
        return "Hello, world!";
    }
}

Which you would call from your template using:

{{ craft.hello.message }}

On a side note, a really good place to start plugin development is to download and install a plugin template such as BusinessLogic, which provides a basic plugin structure, some sample files, and includes inline documentation for basic business logic kind of functionality.

| improve this answer | |
  • Thanks for pointing to BusinessLogic. Pure gold! – Jannie Theunissen Jan 17 at 7:00
1

Here is my corrected code ...

<?php
namespace Craft;

class HelloVariable
{
    public function getMessage($msg)
    {
        return $msg;
    }
 }

and for the template...

{% extends "_layouts/cp" %}

{% set title = "Hello World"|t %}

{% set content %}

<h2>{{ craft.hello.getMessage('Say something original...') }}</h2>

{% endset %}

which prints in the control panel...

 Hello World
Say something original...
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.