Dynamic Button labels using message tables

From The Foundry MODO SDK wiki
Jump to: navigation, search

Description:

This snippet shows how to create a dynamic label for a command, ready for internationalization.

Code:

"""
Labels displayed in Modo's UI should always come from a message table in a config file for the sake of internalization.
This snippet shows how to create a dynamic label for a command.
 
Copy the config fragment to it's own file and save it as something like "MyTable.cfg" in the "config" folder.
Drop this python script into the "lxserv" folder of your scripts directory.
Add the command 'dynamic.label' to some form, using the form editor. 
You should see it labeled as Result: Something
 
Notice the %1 syntax in the config fragment below used for substitution. 
"Result: %1" becomes "Result: Something".
 
Using this syntax allows translators to deal with different languages' semantics when adding translations to the config file.
Hence this method should be preferred over constructing strings manually in your own code.
 
 
MyMessages.cfg:
---------------------
<?xml version="1.0"?>
<configuration>
	<atom type="Messages">
		<hash type="Table" key="myTableKey.en_US">
			<hash type="T" key="myTableEntryKey">Result: %1</hash>
		</hash>
	</atom>
</configuration>
 
"""
import lx
import lxifc
import lxu.command
 
 
class CmdDynamicButtonName(lxu.command.BasicCommand):
    def __init__(self):
        lxu.command.BasicCommand.__init__(self)
 
    def cmd_Flags(self):
        return lx.symbol.fCMD_MODEL | lx.symbol.fCMD_UNDO
 
    def basic_Enable(self, msg):
        return True
 
    def basic_Execute(self, msg, flags):
        lx.notimpl()
 
    def basic_ButtonName(self):
 
        myVariable = 'Something'
        msg_svc = lx.service.Message()
        msg = lx.object.Message(msg_svc.Allocate())
 
        # This selects the message "Result: %1" by it's key "myTableEntryKey" for 
        # the current language (en_US by default) from the message table of 
        # the config file.
        msg.SetMessage ('myTableKey', 'myTableEntryKey', 0)
 
        # Replaces the '%1' substring with the content of myVariable
        msg.SetArgumentString (1, '%s' % myVariable)
 
        myButtonName = msg_svc.MessageText(msg)
        #Result: 'Result: Something'
 
        return myButtonName
 
lx.bless(CmdDynamicButtonName, "dynamic.label")