Question

I have two variables, one is $video_id which contains a youtube or vimeo video id. The other is $video_type which contains either 'youtube' or 'vimeo'.

I have two functions in php,
youtube_embed($id, $width, $height)
vimeo_embed($id, $width, $height)

What I want to do is call this function passing it in the $video_id

I could do:

{if $video_type == 'youtube'}
    {$video_id|youtube_embed:123:123}
{elseif $video_type == 'vimeo'}
    {$video_id|vimeo_embed:123:123}
{/if}

But I am wondering if you can have variable modifier names, something like

{$video_id|`$video_type`_embed:123:123}
Was it helpful?

Solution

That's a Bad Idea, even if you could.

Your code would be much clearer to read, maintain and extend in the future if you did:

{$video_id|video_embed:$video_type:123:123}

and then in PHP check for $video_type and pass it on to the appropriate modifier, rather than trying to handle it at the template level.

function video_embed($video_id, $video_type, $x, $y){
    switch($video_type){
        case('youtube'):
            youtube_embed($video_id, $x, $y);
            break;

        case('vimeo'):
            vimeo_embed($video_id, $x, $y);
            break;

        default:
            throw new UnsupportVideoTypeException($video_type);
    }
}

When you inevitably need to support a new video type you will only have to add some code in the video_embed function in PHP, rather than editing every template that displays a video.

For the record, no it doesn't appear possible. Looking at the source code for Smarty it doesn't try to evaluate variables when it's expecting a modifier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top