Using the TinyMCE template plugin in Drupal

78 comments

On my RC news blog there are quite a few elements that are used on a regular basis in news posts (eg specifications tables, etc). It's a major pain in the ass recreating these elements again and again, and now that I've got a few other writers on board, it's getting hard to keep everything consistent.

Tonight I decided to create about half a dozen small template snippets that would be used as the framework for these elements and allow the writers to just fill in the blanks. To pull it all together and make it easy to use, I used TinyMCE's template plugin to load the templates straight into the text editor.

It's a breeze to setup, here's how:

  1. In your TinyMCE module directory, find the plugin_reg.php file and add the following lines just before the return $plugins; line.
    $plugins['template'] = array();
    $plugins['template']['theme_advanced_buttons3'] = array('template');
    $plugins['template']['template_external_list_url'] = array(0=>"/templates/templates.js");
                   
  2. Enable the template plugin for the relevant users in your TinyMCE configuration (Site Configuration > TinyMCE).
  3. Create a directory called templates in the root of your site (or wherever you like, just remember to change the code in step 1) and create a file called templates.js with the contents:
    var tinyMCETemplateList = [
            // Name, URL, Description
            ["Specifications Table", "/templates/specifications.htm", "Creates a specification table"],
    ];             

    Create as many templates as you like, one line for each.
  4. Create .htm files for each of your templates with the contents:
            <!-- This will not be inserted -->
    <div class="mceTmpl">
            <!-- insert template content here -->
    </div>
                   
  5. Save and upload all the files.

You should notice a little template button (Template Icon) in your TinyMCE editor, which will load all the templates you specified in the templates.js file.

And here is how it will look when inserting the templates

TinyMCE Templates

NOTE: When you upgrade TinyMCE, be sure not to replace your modified plugin_reg.php.

Got any other TinyMCE tips or tricks to help make editing your posts better?

Update: Fixed a problem in the code producing the Invalid argument supplied for foreach() php error - Thanks to S Gifford for the solution.


Comments

I've always wanted to do

I've always wanted to do this, thanks.

"Create a directory called templates in the root of your site..."

Why not add the template folder in the same place as your themes and modules - in sites/all?

I didn't do this because I

I didn't do this because I wanted to keep it nice and simple for my site, but it will work anywhere. I'll modify the post now.

The standard release of

The standard release of Drupal, known as Drupal core, contains basic features common to content management systems. These include user account registration and maintenance, menu management, RSS-feeds, page layout customization, and system administration. Thanks.

Sounds mighty useful. Could

Sounds mighty useful.

Could you please consider sharing a screenshot of how this ends up looking like at the point of data entry? I got the idea, but am unable to visualize what you are doing this for.

Great Idea

I've updated the post now with a screenshot of what it looks like when inserting the template.

Nice trick, thanks. Is there

Nice trick, thanks.
Is there any way to incorporate such feature direct in drupal theme?

Hmm, good question. It might

Hmm, good question. It might be possible by overriding the theme_tinymce_theme theme function in the template.php file as per the README.TXT file in the tinymce module.

I haven't tested this but it might work:

<?php
function phptemplate_tinymce_theme($init, $textarea_name, $theme_name, $is_running) {
  switch ($textarea_name) {
    // Disable tinymce for these textareas
    case 'log': // book and page log
    case 'img_assist_pages':
    case 'caption': // signature
    case 'pages':
    case 'access_pages': //TinyMCE profile settings.
    case 'user_mail_welcome_body': // user config settings
    case 'user_mail_approval_body': // user config settings
    case 'user_mail_pass_body': // user config settings
    case 'synonyms': // taxonomy terms
    case 'description': // taxonomy terms
      unset($init);
      break;

    // Force the 'simple' theme for some of the smaller textareas.
    case 'signature':
    case 'site_mission':
    case 'site_footer':
    case 'site_offline_message':
    case 'page_help':
    case 'user_registration_help':
    case 'user_picture_guidelines':
      $init['theme'] = 'simple';
      foreach ($init as $k => $v) {
        if (strstr($k, 'theme_advanced_')) unset($init[$k]);
      }
      break;
  }

  /* Example, add some extra features when using the advanced theme. */
 
  // If $init is available, we can extend it
  if (isset($init)) {
    switch ($theme_name) {
      case 'advanced':
        $init['plugins'] = array('template');
        $init['template_external_list_url'] = array("/templates/templates.js");
        break;
    }
  }

  // Always return $init
  return $init;
}
?>

about tinymce

After success full configuration in drupal I am not able to use Tinymce in my drupal.Any help is needed.

I'm not really sure whether

I'm not really sure whether I can help because I don't really know what sort of trouble you're having.

Have you read the TinyMCE documentation here ?

path problems with drupal tinyMCE template ?

i'm sort of new to the whole drupal thing, though i've done lots of custom web programming and your plugin solution is fantastic. however, i've tried lots of configs including yours but kept getting ....

-- warning: Invalid argument supplied for foreach() in /home/waterfr1/public_html/modules/tinymce/tinymce.module on line 546. --

which, upon inspection, is an add of buttons in the main mod.

i'm thinking it's a path issue but have tried every combination and it's no use.

any help would be fantastic.

thanks in advance,
jeff

Hi Jeff, I've never seen

Hi Jeff,

I've never seen that problem before. I would assume that it's a problem with your plugin_reg.php file and the _tinymce_plugins() function inside that not returning a proper array.

Was it producing this error when you first installed TinyMCE (without making any modifications to that file)?

Nick

Similar Problem

Thanks for the article. I do have to commiserate with a few of my fellow commenters, however. I'm having the same issue. The template plugin works for me, but I get the following error twice, and only when I have the three configuration lines from your article enabled:

* warning: Invalid argument supplied for foreach() in /Applications/xampp/xamppfiles/htdocs/cfb/sites/all/modules/tinymce/tinymce.module on line 546.
* warning: Invalid argument supplied for foreach() in /Applications/xampp/xamppfiles/htdocs/cfb/sites/all/modules/tinymce/tinymce.module on line 546.

Any insight?

Hi Steven, I'll have another

Hi Steven,
I'll have another look this weekend and see if I can work out what is going on.

Same Error: Solution?

$plugins['template'] = array();
$plugins['template']['theme_advanced_buttons3'] = array('template');
$plugins['template']['template_external_list_url'] = array(0=>"/templates/templates.js");

Note the third line is an array instead of
$plugins['template']['template_external_list_url'] = 0=>"templates/templates.js";

which has the last line not as an array.

I *think* this is the problem.

Thanks for the instructions!

template_external_list_url is an array...

I got this to work with:

$plugins['template']['template_external_list_url'] = array('/files/templates/templates.js');

Other plugin variables are passed this way as well. See the line for the Font Plugin in plugin_reg.php:
$plugins['font']['extended_valid_elements'] = array('font[face|size|color|style],span[class|align|style]');

Thanks for the great tutorial. Just what I was looking for.

Hey, great tutorial! I

Hey,

great tutorial! I checked it out myself and it returned the same error of an invalid argument on tinymce.module on line 546. Did you manage to think of a solution to this problem? I'm also assuming this tutorial is for a drupal 5x installation.

Thoughts?

Thanks alot!
-Cameron

Thanks guys for the

Thanks guys for the comments. I have updated the post now with S Gifford's code so that it doesn't generate the PHP error.

Above fix works for me

Thanks for the great tutorial, the above fix, http://www.schoonzie.com/using-tinymce-template-plugin-drupal#comment-35
works for me, no problem.

I got foreach error like most others here, putting it into the array as suggested smoothed it out, works perfectly!

template woes

Hi, I was wondering if you would be so kind as to share one of your templates with us.

I have a couple of odd issues...

1) TinyMCE inserting my template twice. Solved by adding the comments to the template, i.e.

div class="mceTmpl"
!-- mceTmplBegins --
div id="Tmplcontainer"
div id="Tmplcontent" Sample /div
/div
div id="Tmplsidebar" Sample /div
!-- mceTmplEnds --
/div

The "Sample" placeholder text is for another issue - even if I set a min-height on the divs e.g 100px (the divs appear 100px high in the editor), but TinyMCE thinks they are empty and collapses them, so its nigh on impossible to get the cursor where its needed... the placeholder text solves that dilemma.

Sorry about the weird looking code, but your input filter was stripping out the DIV tags and comments.

2) When using a pure CSS / DIV layout hitting the return key for a new paragraph generates a new DIV container of the same name as the containting DIV! Mad...

Only workaround I have found so far is to use a table to wrap it all up, which seems to work fine.

Have you used pure CSS layouts for your templates? If so, sure like to hear how you got them working.

Hi Jeff, Thanks for the

Hi Jeff,
Thanks for the comment. One of the templates that I use is
<!-- This will not be inserted -->
<div class="mceTmpl">
<div class="image_caption">
<img src="/files/ZeroRC-feedburner.jpg" /><br />
Sample Caption
</div>
</div>
It appears as you see in the screenshot in the post, so I can't really help with the problem you are having. If you like I'd be happy to take a look - send me an email via the contact form with your details.

Underscores are the devil

If you've followed all the steps here, looked at the moxiecode docs, and the tinymce drupal module docs, and you swear that everything is right, but no templates are showing up in the drop down box - make sure you don't have any underscores ( _ ) in your file names. If you do, change them to hyphens ( - ), update your code, then refresh your edit page and behold the glory of templates.

Thank you

Wow, after so many attempts to insert html from dropdown in CCK node reference to tinyMCE, I had just about given up. I found your article and with a few additions to once of my modules and the settings as above, I have a fully fledged template integrated node.

Basically I have a content type template setup in Drupal, and output the headers as text. So instead of giving an actual directory, I get the Drupal Menu system to handle it dynamically. Without you I could not have made it simpler.

Thank you.

Great advice

Really useful advice. I adapted your instructions to install the template functionality into my wordpress installation. The three lines I had to change were:

if ( $teeny ) {
....
} else {
$plugins = array( 'safari', 'inlinepopups', 'autosave', 'spellchecker', 'paste', 'wordpress', 'media', 'fullscreen', 'wpeditimage', 'wpgallery', 'template' );
}

if ($teeny) {
...
} else {
...
$mce_buttons_3 = apply_filters('mce_buttons_3', array('template'));
...
}

// TinyMCE init settings
$initArray = array (
... ,
... ,
'template_external_list_url' => '/templates/templates.js'
);

I should have mentioned the

I should have mentioned the changes were made to wp-admin/includes/post.php

You might want to check this

You might want to check this out http://drupal.org/project/wysiwyg_template

Formating font sizes in TinyMCE

I am very very new with Drupal, so I'm coming across to many challenges.

I don't know if I'm too stupid or too ignorant but I just can't change the font size when creating a page, and this makes me to fight with my boss.

I first tried writing in Kwrite then copy from it and paste into page body but it didn't work for me.

Then I tried ctrl A - font size - save, and nothing changed.

Please can somebody urgently assist, and thanx in advance.

Yours is a fine lesson. It

Yours is a fine lesson. It would save users a lot of time and energy as it is easy and handy to work with. thanks for incorporating the innovative ideas into your work.

I am glad to learn how using

I am glad to learn how using the tinymMCE template plugin in drupal you can create web pages directly on your site by logging on any computer. thanks for the nice information.

I've immensely been benefited

I've immensely been benefited by the discussion on using the tinyMCE template plugin in drupal which helps load the templates straight into the text editor. It is a very valuable information. thanks.

I always find valuable lesson

I always find valuable lesson on different useful drupal plugins in the site. The tutorial on using tinymce template plugin is very comprehensive and refreshing. Thanks for sharing.

I always find valuable lesson

I always find valuable lesson on different useful drupal plugins in the site. The tutorial on using tinymce template plugin is very comprehensive and refreshing. Thanks for sharing.

Is it yours too

Very nice site! is it yours too

As a developer I the benefits

As a developer I the benefits of using the TinyMCE template plugin in Drupal and understand the importance of the tutorial. Thanks for informative post.

Testking 640-802

I am simply out of words after reading your blog. I want to appreciate the way you handled such a complicated subject.

Nice

Excellent work with broad vision and nice approach,I really appreciate such work.

Using this plugin in Drupal

Using this plugin in Drupal will enhance their features in a very proper way.I am sure that this is a template which gives us satisfactory results in in a proper way.I think it is better to obtain this template so that one could achieve success in it.

Step ahead

Any innovation in IT is actually a step ahead of mankind in progress.

wow it is great work i

wow it is great work i appreciate your efforts keep it up.
keep sharing this kinda informative articles.

good article

great post thanks a lot for sharing your thoughts and lots of informative material in one place.

I am not familiar with Drupal

I am not familiar with Drupal and after your tutorial above, I will build myself a Drupal website. Thank you.

adipex

Hello!

Canada Goose Expedition

full correctly provides obtained varieties of good celeb cross our planetin addition to canada gooseline about extremely regarded clothiersQuite movie makers maintain many 5 to ten several years really have to cope withride for these miniature wonders of natureMaybe the remarkable journey appeared too difficult for thisCanada goose clothes appears elegant awesome gentle charming and light-weightAre you enthusiastic about the model ofuniversity youth definitely canada goose outfits on their attire higher compared to the sensation their extremely personal Canada Goose Expedition and journey inside of a "V"-shaped formationCanadian geese are herbivores but may possibly occasionally feed on tiny fishin accordance with a Highlights Magazine picture flaunts red and black plumage-hardly the pristine white colour foremployed withBy taking time to successfully aspect of normally the factors referred to this specificwill use blinds that happen to be super snug ( heated) concealed and spacious for you as well as crew- Tryweathercarsonary blogspot blogtruenoro blogspot blogmiguellar blogspot blog Canada goose reveal to you the

We, as a country, are so

We, as a country, are so afraid of stepping on someones rights that we've gotten ourselves boxed into acceptiong less than par performance in lieu of canning someone off the bat who you know isn't good in the position or for the company. It's pathetic!

I am glad to learn how using

I am glad to learn how using the tinymMCE ideal plugin in drupal you can create web pages directly on your grounds by logging on any computer. confidence for the nice information.

cheap ambien

Hello!

buy ambien

Hello!

nike shox nz dame

monster beats
Alt du måtte til gi viste seg å være ta en klar minutter og så tror. Hva slags for ad ville jeg lik du kan lese? Hva ville interesse meg? Jeg ikke ansett knocking det som du prøve . Jeg ta gjort denne situasjonen . Mange ganger. Men jeg ha for å virkelig bekjempe en oppfordrer videre og dessuten ta deres øyeblikk ikke å nevne skrive.
,beats by dre solo hd test
Hvis sikkerhet faktisk en bredt bekymring beslektet med din, så du burde å faktisk som kan en sikkerhet involverer din nye nettsted forbedrer på hvert trinn kl aksjer når du trenger å virtual private for å hjelpe deg til web nettsteder hosting.
beats by dr dre
Simply passord forårsake problemer siden de blir grei til figur for . En analyse alle passord der skaffe blitt hacket har vist denne de vanlige mennesker gjøre bruk av dette lite antall opprettet av lett identifiserbare ord, typer å gi en brukerne navn med adresse.
http://www.northfacenorway.eu

This news of post is so

This news of post is so amazing but I know now after read this. This site always post some beautiful ideas, so thanks for your post.

The standard release of

The standard release of Drupal, known as Drupal core, contains basic features common to content management systems. These include user account registration and maintenance, menu management, RSS feeds, page layout customization, and system administration. The Drupal core installation can be used as a brochureware website, a single or multi user blog, an Internet forum. Thanks.
Regards,
email search

Extend Drupal's core

Extend Drupal's core capabilities and add new features or customize Drupal's behavior and appearance. Because of this plug-in extensibility and modular design, Drupal is sometimes described as a content management framework. Drupal is described as a web application framework, as it meets the generally accepted feature requirements for such frameworks. Thanks.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options