我的问题是以下代码:
\documentclass{article}
\usepackage[english]{babel}
\begin{document}
\def\suplang{english}
\ifx\languagename\suplang
Supported language: \languagename
\else
Not supported language: \languagename
\fi
\end{document}
结果是“不支持的语言:英语”,而不是“支持的语言:英语”。我做错了什么?
答案1
出于实施原因,替换文本的\languagename
第一个字符的类别代码为 12;就此而言\ifx
,
e
11n
11g
11l
11i
11s
11h
11
和
e
12n
11g
11l
11i
11s
11h
11
是不同的。事实上,如果你这样做
\documentclass{article}
\usepackage[english]{babel}
\begin{document}
\edef\suplang{\string english}
\ifx\languagename\suplang
Supported language: \languagename
\else
Not supported language: \languagename
\fi
\end{document}
那么输出是
你有必要做那项生意吗?当然不需要了。
\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\supported}[3]{%
\ifnum\pdf@strcmp{\languagename}{#1}=\z@
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{#2}{#3}%
}
\makeatother
然后
\supported{suplang}
{Supported language: \languagename}
{Not supported language: \languagename}
将工作。
\documentclass{article}
\usepackage[english]{babel}
\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\supported}[3]{%
\ifnum\pdf@strcmp{\languagename}{#1}=\z@
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{#2}{#3}%
}
\makeatother
\def\suplang{english}
\begin{document}
\supported{\suplang}
{Supported language: \languagename}
{Not supported language: \languagename}
\end{document}
对于真分支和假分支的替代定义\else
:\fi
\documentclass{article}
\usepackage[english]{babel}
\usepackage{pdftexcmds} % to work with all engines
\makeatletter
\newcommand{\issupported}[1]{%
TT\fi\ifnum\pdf@strcmp{\languagename}{#1}=\z@
}
\makeatother
\def\suplang{english}
\begin{document}
\if\issupported\suplang
Supported language: \languagename
\else
Not supported language: \languagename
\fi
\end{document}
答案2
这回答egreg 已经解释了问题中例子出现意外结果的原因,并且给出了解决问题的几种方法。
包iflang
将比较的内部内容包装\languagename
在一个简单的宏中\IfLanguageName
。问题的例子变成:
\documentclass{article}
\usepackage[english]{babel}
\usepackage{iflang}
\begin{document}
\IfLanguageName{english}{%
Supported language: \languagename
}{%
Not supported language: \languagename
}
\end{document}