1

I sometimes see the defun function in Smarty. Unfortunately the file compiler.defun.php is not documented, neither could I google anything usefull. So what does defun mean, and what exactly should it do?

Reading the code I reason that it is some sort of function creation, but I can´t think of why someone would define functions withhin a smarty template. Google results often mention iteration recursions, but without giving an example on how defun is related to that.

Thanks

Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44

1 Answers1

2

Well it seems that defun is similar (or the same) as function. My guess is that defun is some yoda-speak for "function definition".

I'd used that for generating a nav container, asymmetric and dynamic in nature, that required to copy some boilerplate html lists with simple mods to their class attributes. Actually I've found something similar example of generating a nested menu. Also I've used it to create sort of ad hoc simple view helpers for ZF2 forms.

One could argue whether declaring functions in templates makes for a readable and/or maintainable code, but it's an option.

Community
  • 1
  • 1
guessimtoolate
  • 8,372
  • 2
  • 18
  • 26
  • 2
    [defun](http://en.wikipedia.org/wiki/Defun) historically comes from "***de***fine ***fun***ction" (no yoda about it), a LISP-y term. There are other "def*" forms as well in such language families. – user2864740 Feb 22 '15 at 22:12
  • Great, thank you! Did you encounter any performance issues as I would imagine in an eval()-like-construct, or is defun a convenient alternative to {include}? – Zsolt Szilagyi Feb 23 '15 at 09:00
  • I haven't benchmarked it to be honest, but I can't imagine `include` to be faster (in the recursion scenarios mentioned) than `function`, since it has to, at some point, fetch the template from the disk. I think consecutive `include` call for the same template could be cached with something like opcache, but it's still more than defining a function. I did come across an interesting discussion on smarty forums touching this subject: http://www.smarty.net/forums/viewtopic.php?p=18153 . I guess it all depends on a use case, but for nested menus I'd go with recursive `function` calls. – guessimtoolate Feb 23 '15 at 09:13