Domanda

I am using the MessageFormatter class to format translated strings to display to the end user.

The catch is that I also need to insert some html markup into the final result. For example, the string might just be Peter liked a photo, however, I need the final result to contain markup:

<a href="blah.com">Peter</a> liked <a href="blah2.com">a photo</a>

After doing lots of research, in particular, these questions

I decided to use this approach:

{1}{0}{2} liked {3}a photo{4}

Where:

{0} = Peter
{1} = <a href="blah.com">
{2} = </a>
{3} = <a href="blah2.com">
{4} = </a>

This has worked pretty well, besides being a bit cumbersome. However, the main reason I didn't want to include the markup into resource bundle strings was because, sometimes, I want the strings returned without the HTML tags.

The issue is that if I just pass 1 parameter (Peter) to MessageFormatter, it complains that I have missing parameters.

One work around I could do is to pass this ({1} to {5} would be empty strings):

{0} = Peter
{1} = 
{2} = 
{3} = 
{4} = 

However, this is extremely cumbersome and not very nice.

Is there anyway I can mark a parameter as optional (essentially, to just ignore the parameter, if a value for it is not passed in) in a message format string?

È stato utile?

Soluzione

In PHP 5.5 this is now possible as stated in the changed functions guide.

MessageFormatter::format() and related functions no longer error when an insufficient number of arguments have been provided. Instead, the placeholders will not be substituted.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top