# org-mode source block: conditional header

How can I modify the header of a source block dynamically, based on the backend used to export my org-mode document? Specifically, I want the header to include :results output html when the file is exported to HTML, and :results output latex when the file is exported to LaTeX.

I believe that I should use the org-export-current-backend variable to achieve this, but I have been unable to write a header that does what I need.

For example, I think I could include an if call in the header. Unfortunately, this example triggers the HTML build correctly but not the LaTeX one (I can successfully export to LaTeX by inverting the if conditional):

#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) html latex)

(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))

#+end_src


I did not find a direct answer to my question, so I turned to an alternative that works almost as well as what I had in mind: Org-Mode Macros. In this example, we use the conditional-header macro to "decorate" the source block and dynamically change the header based on the output format. This org-mode document thus exports automatically to both PDF and HTML without altering the code.

#+MACRO: conditional-header (eval (concat "#+header: :results output " (prin1-to-string org-export-current-backend)))

#+begin_src emacs-lisp :exports both
(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))
#+end_src


I think you just needed to add quotes around the values html and latex in the header elisp snippet as follows:

#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) "html" "latex")

(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))

#+end_src


Then the code block seems to generate the right results depending on the org-export-current-backend variable.

• Thanks for giving this a shot! Unfortunately, the code does not seem to be rendered properly when exported to PDF or HTML. The correct code appears in a source "block", but as raw html or LaTeX rather than a properly formatted list. Jun 19, 2021 at 19:24