【问题标题】:Switch Case Conditional output in LatexLatex 中的 Switch Case 条件输出
【发布时间】:2017-10-14 22:41:26
【问题描述】:

我想写一份结构如下的报告:

   \begin{document}
     \input[option=a]{class}
     \input[option=b]{class}
     \input[option=c]{class}
     \input[option=d]{class}
   \end{document}

class.tex 的内容如下:

   here are some shared content

   switch(option)
     case a
       some text a
     case b
       some text b
     case c
       some text c
     case d
       some text d
   endswitch

   Here maybe more shared content.

在 Latex 中有什么方法可以做到这一点吗?

【问题讨论】:

  • 给定 LaTeX 输入的预期输出是什么?也就是说,\input[option=c]{class}(比如说)翻译成什么?
  • 我已经更新了。我想输出单个 tex 文件的不同部分。

标签: switch-statement latex


【解决方案1】:

一种简化的方法是使用if else fi logic 的逻辑语句

.tex文件的顶部设置一个开关

\newif\ifswitch

默认值为false。要将值设置为true,请使用

\switchtrue

然后在文本文件中使用

\ifswitch

   <<text to include if switch is true>>

\else

   <<text to include if switch is false>>

\fi % ends the if statement

因此,对于您的特定问题,您可以使用一组开关

\newifConditionA
\newifConditionB
\newifConditionC
\newifConditionD

这不像使用switch 语句那样优雅,但允许您同时需要来自A 和C 的文本的条件。

这里讨论的参考是 two versions of a document with 'if else' logic statements

【讨论】:

    【解决方案2】:

    您可以使用以下(粗略的)方法来识别要从文件中提取内容的文本组件:

    \documentclass{article}
    
    \usepackage{filecontents}
    \begin{filecontents*}{class.tex}
       switch(option)
         case a
           some text a
         case b
           some text b
         case c
           some text c
         case d
           some text d
       endswitch
    \end{filecontents*}
    
    \usepackage{catchfile}
    
    % \inputclass{<file>}{<from>}{<to>}
    \newcommand{\inputclass}[2]{%
      \CatchFileDef{\class}{class.tex}{}%
      \long\def\classsegment##1#1 ##2 #2##3\relax{##2}%
      \show\classsegment
      \expandafter\classsegment\class\relax
    }
    
    \begin{document}
    
    \inputclass{case c}{case d}
    
    \inputclass{case a}{case b}
    
    \inputclass{case d}{endswitch}
    
    \inputclass{case b}{case c}
    
    \end{document}
    

    相关:

    最后一种是使用catchfilebetweentags package 的适应性更强的方法。这需要在您的代码中插入适当的标签,这可能没有那么有用。您还可以使用listings 来包含来自外部文件的特定代码行。

    【讨论】:

      【解决方案3】:

      据我了解,您想要的是为文本的每个不同部分更新函数,同时在一个地方定义函数。

      执行此操作的简单方法是在每个部分的开头更新变量命令。

      开始时:

      \newcommand{\VARIABLENAME}{VARIABLE_1}
      

      在部分:

      \renewcommand{\VARIABLENAME}{VARIABLE_2}
      

      还有更高级的方法可以做到这一点,包括定义变量,但值得一提的是,这更易读且更易于实现。

      注意:如果你打算做一些比类更动态的东西,我建议用另一种语言实现一些东西,比如 python 来用 LaTex 编写文件,因为它通常会提供更多的修改空间。

      【讨论】:

      • 你能用一个例子来说明你的答案吗?
      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 2022-06-16
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      相关资源
      最近更新 更多