Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Best way to convert string variables in templates

Go to End

5 Posts   1453 Views


Community Member, 136 Posts

8 August 2013 at 11:53am


A Page Type has the following TextFields:

I want to be able to display the values of these fields in a template once they have been converted to lowercase and has all non-alphanumeric characters converted to hyphens.

So "What We Do" becomes "what-we-do" - and can be displayed in the template as such. This is so the converted string can be used as a div id for navigation purposes.

I can think of a number of different approaches but not sure which one to take.

Is there a correct or recommended approach for this sort of thing?


Forum Moderator, 5521 Posts

11 August 2013 at 6:07pm

The way I would recommend is a custom getter on your page type. In 3.0 you can pass variables into methods so you only need to define the method once.

public function getFormattedSectionHeading($heading) {
$f = URLSegmentFilter::create();
$t = $f->filter($title);

return DBField::create('Text', $t);

Then use $FormattedSectionHeading($Heading) in your template.

You could also create a new DBField subclass and encapsulate this logic on the field type

<?php class MyFormattableVarchar extends Varchar {
public function AwesomeFormat($heading) {
$f = URLSegmentFilter::create();
$t = $f->filter($title);

return DBField::create('Text', $t);

Then using "Field" => "MyFormattableVarchar" will be possible in $db arrays and your templates will look like $Section1Heading.AwesomeFormat


Community Member, 136 Posts

12 August 2013 at 12:33pm

Edited: 12/08/2013 12:33pm

Thank you for your time Will.

Here's the solution I went for:



class TidyFormatVarchar extends Varchar {

  public function AnchorName() {
    $f = URLSegmentFilter::create();
    $t = $f->filter($this->value);
    return $t;


class MyPage extends SiteTree {
  public static $db = array(
      'Section1Heading' => 'TidyFormatVarchar',
      'Section2Heading' => 'TidyFormatVarchar',


<div id="$Section1Heading.AnchorName" class="section-1">


Community Member, 187 Posts

12 August 2013 at 10:09pm

Just for reference, here's an alternative solution I use:


class StringFieldExtension extends Extension {

	public function CSSSafe() {
		return Convert::raw2url($this->owner->value);


Apply the extension, either YAML:

    - StringFieldExtension

or _config.php

Object::add_extension('StringField', 'StringFieldExtension');

Then in your templates you can use

<div id="$Section1Heading.CSSSafe" class="section-1">


Community Member, 136 Posts

13 August 2013 at 7:13am

Thank you for posting that up kinglozzer - it's tidier than the approach I used.

I like tidy.