如何在LaTeX中根据变量和状态定义输出?

3

我有一些标准文本,但其中的一部分是不同的。但这些不同的部分只有很少存在。

例如,我想要:

\mytext{...}{a}

\mytext{...}{b}

那会产生:

\section{Item: ...}\label{item...}
This is a standard item. Items of type a are very precious.

\section{Item: ...}\label{item...}
This is a standard item. Items of type b are cheap.

一个简单的解决方案是定义命令mytexta和mytextb,但由于我有更多的选项,我想要更像编程语言中的if或switch。有人有这个问题的解决方案吗?


顺便提一下,它应该说“这是一个标准项目”,而不是“an” :-) - ShreevatsaR
感谢,我已经更正了。我不是母语为英语的人。 - Mnementh
这个与Latex相关的问题最好在这个地方提问(尽管也许在那个时候这个StackExchange还不存在?)https://tex.stackexchange.com/questions/265809/if-elseif-and-else-conditionals-in-the-preamble - Marine Galantin
3个回答

4
< p > ifthen 包(包含在标准的 LaTeX 安装中)定义了一个命令 \ifthenelse,使用方式如下:

\usepackage{ifthen}
\ifthenelse{test}{then-code}{else-code}

因此,您可以进行类似以下的操作:

\newcommand\mytext[1]{%
    \ifthenelse{\equal{#1}{a}}{very precious}{%
    \ifthenelse{\equal{#1}{b}}{cheap}{unknown}}}

对于LaTeX编程,我建议您获取一份LaTeX Companion。这是这方面的非常好的参考资料。


2

您可以使用\newif\iffoo来声明一个新的条件。 然后,\footrue或\foofalse将其设置为true或false,并且您可以通过\iffoo ... \else ... \fi来使用它。

还有更多条件语句,请参见TeXbook中的第209页及以下。


有一个例子吗? - Marine Galantin

0

另一个选择是使用etoolbox(适用于XeLaTeX),下面是一个MWE示例

\documentclass{article}

\usepackage{etoolbox}

\begin{document}

\newcommand{\mytext}[1]
{
\ifstrequal{#1}{a} %% make the first comparison
{ %% print text in the first scenario
\section{Item: #1}\label{item.#1}
This is a standard item. Items of type a are very precious.
}
{} %% do nothing if false
\ifstrequal{#1}{b} %% make the second comparison
{ %% print text in the second scenario
\section{Item: #1}\label{item.#1}
This is a standard item. Items of type b are cheap.
}
{} %% do nothing if false
}

\mytext{a}
\mytext{b}
\\

\noindent
We can refer to sections \ref{item.a} and \ref{item.b}

\end{document}

它会产生

my_text


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接